Skip to content

Commit 12c3b94

Browse files
committed
refactor: 73. Set Matrix Zeroes to reduce Space complexity to O(1)
1 parent 4847a02 commit 12c3b94

File tree

1 file changed

+45
-12
lines changed

1 file changed

+45
-12
lines changed

set-matrix-zeroes/gwbaik9717.js

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// m: height of matrix, n: width of matrix
22
// Time complexity: O(m*n)
3-
// Space complexity: O(m+n)
3+
// Space complexity: O(1)
44

55
/**
66
* @param {number[][]} matrix
@@ -10,27 +10,60 @@ var setZeroes = function (matrix) {
1010
const h = matrix.length;
1111
const w = matrix[0].length;
1212

13-
const setY = new Set();
14-
const setX = new Set();
13+
// a flag for iterating rows of the first column
14+
let temp1 = false;
15+
16+
// a flag for iterating cols of the first row
17+
let temp2 = false;
1518

1619
for (let i = 0; i < h; i++) {
17-
for (let j = 0; j < w; j++) {
20+
if (matrix[i][0] === 0) {
21+
temp1 = true;
22+
break;
23+
}
24+
}
25+
26+
for (let i = 0; i < w; i++) {
27+
if (matrix[0][i] === 0) {
28+
temp2 = true;
29+
break;
30+
}
31+
}
32+
33+
for (let i = 1; i < h; i++) {
34+
for (let j = 1; j < w; j++) {
1835
if (matrix[i][j] === 0) {
19-
setY.add(i);
20-
setX.add(j);
36+
matrix[i][0] = 0;
37+
matrix[0][j] = 0;
2138
}
2239
}
2340
}
2441

25-
for (const y of setY) {
26-
for (let x = 0; x < w; x++) {
27-
matrix[y][x] = 0;
42+
for (let i = 1; i < h; i++) {
43+
if (matrix[i][0] === 0) {
44+
for (let j = 1; j < w; j++) {
45+
matrix[i][j] = 0;
46+
}
2847
}
2948
}
3049

31-
for (const x of setX) {
32-
for (let y = 0; y < h; y++) {
33-
matrix[y][x] = 0;
50+
for (let i = 1; i < w; i++) {
51+
if (matrix[0][i] === 0) {
52+
for (let j = 1; j < h; j++) {
53+
matrix[j][i] = 0;
54+
}
55+
}
56+
}
57+
58+
if (temp1) {
59+
for (let i = 0; i < h; i++) {
60+
matrix[i][0] = 0;
61+
}
62+
}
63+
64+
if (temp2) {
65+
for (let j = 0; j < w; j++) {
66+
matrix[0][j] = 0;
3467
}
3568
}
3669
};

0 commit comments

Comments
 (0)