Skip to content

Commit c60cd1d

Browse files
authored
Merge pull request #210 from nhistory/Week14
[Sehwan] Week14 solution with JavaScript
2 parents db26d76 + 833d40a commit c60cd1d

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

set-matrix-zeroes/nhistory.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var setZeroes = function (matrix) {
2+
let rows = new Set();
3+
let cols = new Set();
4+
5+
for (let row = 0; row < matrix.length; row++) {
6+
for (let col = 0; col < matrix[0].length; col++) {
7+
if (matrix[row][col] === 0) {
8+
rows.add(row);
9+
cols.add(col);
10+
}
11+
}
12+
}
13+
14+
for (let row = 0; row < matrix.length; row++) {
15+
for (let col = 0; col < matrix[0].length; col++) {
16+
if (rows.has(row) || cols.has(col)) {
17+
matrix[row][col] = 0;
18+
}
19+
}
20+
}
21+
};
22+
23+
// TC: O(m*n)
24+
// SC: O(m+n)

spiral-matrix/nhistory.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
var spiralOrder = function (matrix) {
2+
// Edge case
3+
if (matrix.length === 0) return [];
4+
5+
let result = [];
6+
let rowStart = 0,
7+
rowEnd = matrix.length - 1;
8+
let colStart = 0,
9+
colEnd = matrix[0].length - 1;
10+
11+
while (rowStart <= rowEnd && colStart <= colEnd) {
12+
// Traverse right
13+
for (let col = colStart; col <= colEnd; col++) {
14+
result.push(matrix[rowStart][col]);
15+
}
16+
rowStart++;
17+
18+
// Traverse down
19+
for (let row = rowStart; row <= rowEnd; row++) {
20+
result.push(matrix[row][colEnd]);
21+
}
22+
colEnd--;
23+
24+
// Traverse left (check if rowStart <= rowEnd to avoid duplicates)
25+
if (rowStart <= rowEnd) {
26+
for (let col = colEnd; col >= colStart; col--) {
27+
result.push(matrix[rowEnd][col]);
28+
}
29+
rowEnd--;
30+
}
31+
32+
// Traverse up (check if colStart <= colEnd to avoid duplicates)
33+
if (colStart <= colEnd) {
34+
for (let row = rowEnd; row >= rowStart; row--) {
35+
result.push(matrix[row][colStart]);
36+
}
37+
colStart++;
38+
}
39+
}
40+
41+
return result;
42+
};
43+
44+
// TC: O(m*n)
45+
// SC: O(m*n)

sum-of-two-integers/nhistory.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
var getSum = function (a, b) {
2+
while (b !== 0) {
3+
if (b > 0) {
4+
a++;
5+
b--;
6+
} else {
7+
b++;
8+
a--;
9+
}
10+
}
11+
return a;
12+
};
13+
14+
// |b| is absolute value of b
15+
// TC: O(|b|)
16+
// SC: O(1)

0 commit comments

Comments
 (0)