|
| 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 | +}; |
0 commit comments