Problem overview
The method setZeroes receives a matrix as an inout [[Int]], with m rows and n columns. Wherever an element is 0, its entire row and its entire column must become 0. The change happens in place and the method 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.
In the first example, the matrix has a single 0 in the middle, at row 1, column 1. The result has a zero middle row and a zero middle column, and four 1s in the corners. The statement expects O(m * n) time and O(m + n) extra space, and mentions a follow-up with O(1) space.
Approach: remember now, clear later
The tempting plan is to clear the row and the column as soon as a 0 is found. It breaks because the new zeros look exactly like the original ones. On the matrix with rows [0, 2, 3, 4], [5, 0, 7, 8] and [9, 10, 11, 12], clearing at once ends with every cell 0, although the correct result keeps 11 and 12 in the last row.
The fix is to separate looking from changing. A first pass over the matrix only records which rows and columns contain a zero. A second pass then sets a cell to 0 if its row or its column was recorded. Two arrays of Bool do the recording: zeroRow has one entry per row and zeroCol has one per column. Together they take O(m + n) space.
For the matrix [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]], the first pass produces:
zeroRow = [true, false, false]
zeroCol = [true, false, false, true]
The second pass clears row 0 and columns 0 and 3, and the result is [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]].
The follow-up removes the two arrays by storing the marks in the first row and the first column of the matrix itself. That needs extra care, because those cells may hold zeros of their own. This lesson uses the two arrays.
Step by step
- Store the dimensions.
matrix.countis the number of rows,m, andmatrix[0].countis the number of columns,n. Every row has the same length, so the first row is enough. - Create the two mark arrays as
vararrays ofBool, allfalse:zeroRowwithmentries andzeroColwithn. They are written to later, so they arevar. - First pass, rows. Loop
iover0..<m. This pass only reads the matrix. - First pass, columns. Inside it, loop
jover0..<n. Together the two loops reach every cell once. - Test for a zero with
matrix[i][j] == 0. - Record it. Set
zeroRow[i]andzeroCol[j]totrue. Several zeros can share a row or a column, and marking again changes nothing. - Second pass, rows and columns. Two more nested loops over
iandjvisit every cell again. - Clear marked cells. If
zeroRow[i] || zeroCol[j], setmatrix[i][j]to 0. A cell becomes 0 exactly when its row or its column held a zero at the start, which is what the marks say.
The solution in Swift
class Solution {
func setZeroes(_ matrix: inout [[Int]]) {
let m = matrix.count
let n = matrix[0].count
var zeroRow = [Bool](repeating: false, count: m)
var zeroCol = [Bool](repeating: false, count: n)
for i in 0..<m {
for j in 0..<n {
if matrix[i][j] == 0 {
zeroRow[i] = true
zeroCol[j] = true
}
}
}
for i in 0..<m {
for j in 0..<n {
if zeroRow[i] || zeroCol[j] {
matrix[i][j] = 0
}
}
}
}
}
Swift details worth knowing:
inoutparameters. Arrays are value types, so a normal parameter is a read-only copy. Withinout, the writes tomatrixreach the caller's array. The caller passes avarwith&, for examplesolution.setZeroes(&grid).[Bool](repeating: false, count: m)builds an array ofmcopies offalse.- Nested subscripts.
matrix[i][j] = 0writes into the row stored insidematrix. It works becausematrixis avar(aninoutparameter counts as one). ||short-circuits. IfzeroRow[i]is true,zeroCol[j]isn't read. The result is the same either way.- Value range. The values can be as large as 2147483647 in size, which fits easily in a 64-bit
Int. The method only compares them with 0.
Complexity
Time: O(m * n). Each of the two passes visits every cell once, and each visit costs a constant amount of work.
Space: O(m + n). zeroRow holds m flags and zeroCol holds n. The follow-up reaches O(1) by keeping those flags in the matrix's first row and column.
Edge cases and common mistakes
- Clearing while scanning. New zeros are indistinguishable from original ones and clear too much. On the matrix with rows
[0, 2, 3, 4],[5, 0, 7, 8]and[9, 10, 11, 12], that approach turns everything into 0. - No zeros.
[[5]]and[[1, 2, 3]]come back unchanged, because no flag is ever set. - A single zero.
[[0]]stays[[0]]. - One column.
[[1], [0], [3]]becomes[[0], [0], [0]]: the zero's row is only one cell, but its column is the whole matrix. - Several zeros in one row or column. Example 2 has two zeros in row 0. Row 0 is marked twice, which is harmless.
- Confusing
mandn.zeroRowis indexed by row and hasmentries, andzeroColis indexed by column and hasn. Swapping them gives an index error on any non-square matrix. - Returning something. The method has no return value. The result is the caller's matrix after the call.
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], [0], [3]]becomes[[0], [0], [0]].[[5]]stays[[5]].
