Skip to content

Commit c21881f

Browse files
committed
Add week 14 solutions: setMatrixZeroes, sumOfTwoIntegers
1 parent 743028c commit c21881f

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

set-matrix-zeroes/yolophg.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Time Complexity: O(rows * cols)
2+
// Space Complexity: O(1)
3+
4+
var setZeroes = function (matrix) {
5+
// number of rows in the matrix
6+
const rows = matrix.length;
7+
// number of cols in the matrix
8+
const cols = matrix[0].length;
9+
// to check if the first row has any zeros
10+
let rowZero = false;
11+
// to check if the first col has any zeros
12+
let colZero = false;
13+
14+
// check if the first row has any zeros
15+
for (let c = 0; c < cols; c++) {
16+
if (matrix[0][c] === 0) {
17+
rowZero = true;
18+
break;
19+
}
20+
}
21+
22+
// check if the first col has any zeros
23+
for (let r = 0; r < rows; r++) {
24+
if (matrix[r][0] === 0) {
25+
colZero = true;
26+
break;
27+
}
28+
}
29+
30+
// use the first row and col to mark zeros
31+
for (let r = 1; r < rows; r++) {
32+
for (let c = 1; c < cols; c++) {
33+
if (matrix[r][c] === 0) {
34+
// mark corresponding col in first row
35+
matrix[0][c] = 0;
36+
// mark corresponding row in first col
37+
matrix[r][0] = 0;
38+
}
39+
}
40+
}
41+
42+
// set matrix elements to zero based on markers in the first row and col
43+
for (let r = 1; r < rows; r++) {
44+
for (let c = 1; c < cols; c++) {
45+
if (matrix[0][c] === 0 || matrix[r][0] === 0) {
46+
matrix[r][c] = 0;
47+
}
48+
}
49+
}
50+
51+
// handle the first row if there was any zero
52+
if (rowZero) {
53+
for (let c = 0; c < cols; c++) {
54+
matrix[0][c] = 0;
55+
}
56+
}
57+
58+
// handle the first col if there was any zero
59+
if (colZero) {
60+
for (let r = 0; r < rows; r++) {
61+
matrix[r][0] = 0;
62+
}
63+
}
64+
};

sum-of-two-integers/yolophg.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Time Complexity: O(log max(a, b))
2+
// Space Complexity: O(log max(a, b))
3+
4+
var getSum = function (a, b) {
5+
// if there is no carry, return a as the result
6+
if (b === 0) return a;
7+
8+
// calculate the sum without carry using XOR
9+
let sum = a ^ b;
10+
11+
// calculate the carry using AND and left shift
12+
let carry = (a & b) << 1;
13+
14+
// recursively call getSum with sum and carry
15+
return getSum(sum, carry);
16+
};

0 commit comments

Comments
 (0)