Skip to content

Commit 4699e1d

Browse files
committed
Add set-matrix-zeroes solution
1 parent a84da2f commit 4699e1d

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

set-matrix-zeroes/Jeehay28.js

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
// 🌈 In-Place Solution (Without extra space)
2+
// The term "in-place" refers to algorithms or solutions that modify the input data directly,
3+
// without needing extra space for a separate copy of the data. In an in-place solution,
4+
// the operations are performed using a fixed amount of extra memory, typically O(1) space, beyond the input data itself.
5+
6+
/**
7+
* @param {number[][]} matrix
8+
* @return {void} Do not return anything, modify matrix in-place instead.
9+
*/
10+
11+
// Time Complexity: O(m * n)
12+
// Space Complexity: O(1)
13+
var setZeroes = function (matrix) {
14+
const rows = matrix.length;
15+
const cols = matrix[0].length;
16+
17+
let firstRowHasZero = false;
18+
let firstColHasZero = false;
19+
20+
// Check if the first row has any zero
21+
for (let c = 0; c < cols; c++) {
22+
if (matrix[0][c] === 0) {
23+
firstRowHasZero = true;
24+
break;
25+
}
26+
}
27+
28+
// Check if the first column has any zero
29+
for (let r = 0; r < rows; r++) {
30+
if (matrix[r][0] === 0) {
31+
firstColHasZero = true;
32+
break;
33+
}
34+
}
35+
36+
// Use first row and column to mark zeros
37+
for (let i = 1; i < rows; i++) {
38+
for (let j = 1; j < cols; j++) {
39+
if (matrix[i][j] === 0) {
40+
matrix[0][j] = 0;
41+
matrix[i][0] = 0;
42+
}
43+
}
44+
}
45+
46+
// Set zeros based on marks in the first row and column
47+
for (let i = 1; i < rows; i++) {
48+
for (let j = 1; j < cols; j++) {
49+
if (matrix[0][j] === 0 || matrix[i][0] === 0) {
50+
matrix[i][j] = 0;
51+
}
52+
}
53+
}
54+
55+
// Handle first row
56+
if (firstRowHasZero) {
57+
for (let c = 0; c < cols; c++) {
58+
matrix[0][c] = 0;
59+
}
60+
}
61+
62+
// Handle first column
63+
if (firstColHasZero) {
64+
for (let r = 0; r < rows; r++) {
65+
matrix[r][0] = 0;
66+
}
67+
}
68+
69+
return matrix;
70+
};
71+
72+
/**
73+
* @param {number[][]} matrix
74+
* @return {void} Do not return anything, modify matrix in-place instead.
75+
*/
76+
77+
// 💪 My initial approach with Set...
78+
// Time Complexity: O(m * n)
79+
// Space Complexity: O(m + n)
80+
var setZeroes = function (matrix) {
81+
let rows = new Set();
82+
let cols = new Set();
83+
84+
for (let i = 0; i < matrix.length; i++) {
85+
for (let j = 0; j < matrix[0].length; j++) {
86+
if (matrix[i][j] === 0) {
87+
rows.add(i);
88+
cols.add(j);
89+
}
90+
}
91+
}
92+
93+
for (row of rows) {
94+
matrix[row] = new Array(matrix[0].length).fill(0);
95+
}
96+
97+
for (col of cols) {
98+
for (let row = 0; row < matrix.length; row++) {
99+
matrix[row][col] = 0;
100+
}
101+
}
102+
103+
return matrix;
104+
};
105+
106+

0 commit comments

Comments
 (0)