Problem overview
The function setZeroes receives an m x n matrix of integers as a [][]int. Wherever an element is 0, its entire row and its entire column must become 0. The change happens in place, and the function returns nothing. Only the zeros present at the start count: a cell that becomes 0 during the process must not clear its own row and column.
For the matrix with rows [1, 1, 1], [1, 0, 1] and [1, 1, 1], the only zero is at row 1, column 1, so the whole middle row and the whole middle column become 0, giving [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. The budget is O(m * n) time and O(m + n) extra space.
Approach: remember now, clear later
The obvious attempt scans the matrix and, on meeting a zero, clears its row and column right away. That breaks the rule about original zeros: the cells just cleared look like zeros to the rest of the scan and clear more rows and columns. For the 3 by 4 matrix [[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]], that approach turns everything into 0, while the correct answer keeps 11 and 12 in the last row.
The fix is to separate looking from changing, in two passes:
- The first pass only reads the matrix. For each original zero, it records that the zero's row and the zero's column must be cleared.
- The second pass clears every cell whose row or column was recorded.
Two slices of booleans hold the records: zeroRow[i] says whether row i contains a zero, and zeroCol[j] says the same for column j. Together they take m + n values, which is the allowed O(m + n) extra space. Several zeros can share a row or a column, and marking it again changes nothing.
The statement mentions a follow-up with O(1) extra space, where the first row and first column of the matrix hold the marks. This lesson uses the two slices.
Step by step
- Store the sizes.
mislen(matrix), the number of rows, andnislen(matrix[0]), the number of columns. Every row has the same length, so the first row tells the column count. - Create the marks with
make([]bool, m)andmake([]bool, n). Every entry starts asfalse. - First pass: loop over the rows
ifrom 0 tom - 1. - Loop over the columns
jfrom 0 ton - 1. The two loops reach every cell once, and this pass changes nothing inmatrix. - Test
matrix[i][j] == 0. At this point nothing has been modified, so every zero seen is an original one. - Mark the cell's row and column:
zeroRow[i]andzeroCol[j]becometrue. - Second pass: loop over the rows again, now that every zero is recorded.
- Loop over the columns again, one cell at a time.
- Clear the cell when
zeroRow[i] || zeroCol[j]is true: setmatrix[i][j]to 0. A cell becomes 0 exactly when its row or its column held a zero at the start.
The solution in Go
func setZeroes(matrix [][]int) {
m := len(matrix)
n := len(matrix[0])
zeroRow := make([]bool, m)
zeroCol := make([]bool, n)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
zeroRow[i] = true
zeroCol[j] = true
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if zeroRow[i] || zeroCol[j] {
matrix[i][j] = 0
}
}
}
}
The Go details worth a closer look:
- The matrix is changed through shared rows. A
[][]intis a slice of row slices. The function gets a copy of the outer slice header, but the rows are shared with the caller, so assigningmatrix[i][j] = 0changes the caller's matrix. That is why the function needs no return value. make([]bool, m)creates a slice ofmbooleans, allfalse, the zero value ofbool. No loop to initialise them is needed.- Two declarations, two lengths.
mcounts rows andncounts columns, so the indices arematrix[i][j]withi < mandj < n. Swapping them is a classic cause of an "index out of range" panic on a non-square matrix. ||short-circuits. WhenzeroRow[i]is true,zeroCol[j]isn't even read. The result is the same either way.
Complexity
Time: O(m * n). Each of the two passes visits every cell once, doing a constant amount of work per cell.
Space: O(m + n). The two boolean slices hold m and n entries. Nothing else grows with the input.
Edge cases and common mistakes
- No zeros.
[[1, 2], [3, 4]]stays as it is, since no mark is ever set. - Everything is zero already.
[[0]]stays[[0]]. - One row or one column.
[[1, 2, 3]]is unchanged, and the column[[4], [0], [6]]becomes[[0], [0], [0]], because the zero's row is the middle one and its column is the only one. - Zeros that share a row.
[[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]]. Row 0 is marked twice, which is harmless. - Clearing while scanning. As described in the approach, doing it in one pass lets new zeros spread. On
[[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]]that gives all zeros, while the two-pass solution gives[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]]. - Using the wrong length for the columns. Taking
nfromlen(matrix)works only for square matrices. The column count comes from a row.
Testing
[[1, 1, 1], [1, 0, 1], [1, 1, 1]]gives[[1, 0, 1], [0, 0, 0], [1, 0, 1]].[[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]gives[[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]].[[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]]gives[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]].[[4], [0], [6]]gives[[0], [0], [0]].[[1, 2], [3, 4]]gives[[1, 2], [3, 4]].
