Sponsored
Sponsored
This approach uses two additional arrays to track the rows and columns that need to be zeroed.
- Traverse the matrix and mark rows and columns that need to be zeroed.
- Then, update the matrix based on the values in these arrays.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for the additional arrays.
1function setZeroes(matrix) {
2 let m = matrix.length;
3 let n = matrix[0].length;
4 let row = new Array(m).fill(false);
5 let col = new Array(n).fill(false);
6
7 for (let i = 0; i < m; i++) {
8 for (let j = 0; j < n; j++) {
9 if (matrix[i][j] === 0) {
10 row[i] = true;
11 col[j] = true;
12 }
13 }
14 }
15
16 for (let i = 0; i < m; i++) {
17 for (let j = 0; j < n; j++) {
18 if (row[i] || col[j]) {
19 matrix[i][j] = 0;
20 }
21 }
22 }
23}This approach uses the matrix itself to track zeroes.
- Use the first row and column as markers.
- Traverse the matrix and if an element is zero, mark its row and column.
- Traverse again and set matrix elements to zero based on marked rows and columns.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1) since the algorithm runs in constant space.
1