Problem overview
The method setZeroes receives matrix, a number[][] with m rows and n columns. Wherever a cell holds 0, its entire row and entire column must become 0. The change happens in place and nothing is returned. Only the zeros present at the start count: a cell that becomes 0 during the process does not clear its own row and column.
For this input:
[0, 2, 3, 4]
[5, 0, 7, 8]
[9, 10, 11, 12]
the matrix afterwards is:
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 11, 12]
The zeros at (0, 0) and (1, 1) clear rows 0 and 1 and columns 0 and 1. The cells that only became 0 clear nothing more, so 11 and 12 stay.
Approach: remember first, clear later
The tempting way is to scan the matrix and, at each 0, zero the row and column immediately. That breaks the rule about original zeros: the new zeros are indistinguishable from the old ones, and later in the scan they would clear rows and columns that should stay. On the example above it zeroes everything, including 11 and 12.
The fix is to split the work into two passes:
- Record. Scan the matrix without changing it, and note which rows and which columns contain a zero. Two boolean arrays are enough:
zeroRow[i]for rowiandzeroCol[j]for columnj. - Clear. Scan again. A cell becomes 0 if its row is marked or its column is marked.
Several zeros can share a row or column, and marking twice changes nothing. The marks cost m + n booleans, which fits the O(m + n) extra-space limit. The follow-up in the statement, O(1) space, stores the marks in the matrix's first row and first column instead; this lesson keeps them in separate arrays.
On the example, the first pass leaves zeroRow as [true, true, false] and zeroCol as [true, true, false, false]. The second pass clears every cell in rows 0 and 1 and in columns 0 and 1, and leaves the bottom-right two cells alone.
Step by step
- Store the dimensions:
mismatrix.length(the rows) andnismatrix[0].length(the columns). Every row has the same length. - Create the marks:
zeroRowwithmvalues andzeroColwithnvalues, allfalse. Writing down the zeros first is what stops new zeros from being mistaken for old ones. - Loop over the rows with
ifor the first pass. This pass only reads the matrix. - Loop over the columns of row
iwithj, so the two loops reach each cell once. - Test
matrix[i][j] === 0. - Mark both: set
zeroRow[i]andzeroCol[j]totrue. - Start the second pass with another loop over the rows. Every zero is recorded now, so cells can change safely.
- Loop over the columns again.
- Clear marked cells: if
zeroRow[i] || zeroCol[j], setmatrix[i][j]to 0.
The solution in TypeScript
class Solution {
setZeroes(matrix: number[][]): void {
const m = matrix.length;
const n = matrix[0].length;
const zeroRow: boolean[] = new Array(m).fill(false);
const zeroCol: boolean[] = new Array(n).fill(false);
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
zeroRow[i] = true;
zeroCol[j] = true;
}
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (zeroRow[i] || zeroCol[j]) {
matrix[i][j] = 0;
}
}
}
}
}
Some TypeScript details:
new Array(m).fill(false)makes an array ofmbooleans. The annotationboolean[]documents the intent and is checked by the compiler, but it disappears when the code is compiled to JavaScript.===against==.matrix[i][j] === 0compares without any conversion, so it matches only the number 0. With==other values such as an empty string would also equal 0, although anumber[][]never holds them.conststill allows changes inside.zeroRowis declaredconst, yetzeroRow[i] = trueis fine: only reassigning the variable itself is forbidden.voidand in-place work. Arrays are passed by reference, so the method changes the caller's rows. Nothing needs to be returned.- Number range. Values can be as large as 2^31 - 1, which a
numberholds exactly. The code only compares against 0 and assigns 0, so no arithmetic is involved.
Complexity
Time: O(m * n). Each of the two passes visits every cell once.
Space: O(m + n). zeroRow has m entries and zeroCol has n. Everything else is a handful of variables.
Edge cases and common mistakes
- Clearing during the first scan. Zeroing the row and column at once makes new zeros spread further. On the example the matrix becomes all zeros, including the 11 and 12 that should stay.
- No zeros. Nothing is marked, so the matrix is unchanged:
[[1, 2, 3]]stays[[1, 2, 3]]. - A single cell.
[[0]]stays[[0]]and[[5]]stays[[5]]. - Sharing one array for all marks. Building the marks as an array of arrays with
new Array(m).fill([])puts the same inner array in every slot, so a change through one index shows in all. Here the marks are flat booleans, which are copied by value, so this problem does not arise. - Rows and columns mixed up.
mcounts rows and goes withzeroRowand the first index.ncounts columns and goes withzeroColand the second index. - Zeros in the same row or column. A row with two zeros is marked twice, which is harmless.
Testing
[[1, 1, 1], [1, 0, 1], [1, 1, 1]]becomes[[1, 0, 1], [0, 0, 0], [1, 0, 1]].[[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]becomes[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]].[[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]]becomes[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]].[[1, 2, 3]]stays[[1, 2, 3]].
