Problem overview
The function set_zeroes receives matrix, a &mut Vec<Vec<i32>> with m rows and n columns. Wherever a cell holds 0, its entire row and its entire column must become 0. The change is made in place and nothing is returned. The budget is O(m * n) time and O(m + n) extra space.
One rule matters: only the zeros present at the start count. A cell that becomes 0 during the process doesn't clear its own row and column. For [[1, 1, 1], [1, 0, 1], [1, 1, 1]] the single zero sits in row 1 and column 1, so the result is [[1, 0, 1], [0, 0, 0], [1, 0, 1]].
Approach: remember now, clear later
The tempting solution scans the matrix and, on meeting a zero, clears its row and column right away. That fails because the cells it just zeroed look exactly like original zeros, so the scan clears even more. On the 3 by 3 example above, the scan zeroes row 1 and column 1, then keeps going and treats the new zeros as original, so the answer comes out wrong (the exact output is shown under common mistakes).
The fix is to split the work into two passes:
- The first pass only reads the matrix. For every zero it finds, it marks the zero's row and the zero's column in two boolean vectors.
- The second pass writes. A cell becomes 0 if its row or its column is marked.
The marks take m + n booleans, which matches the lesson's O(m + n) space limit. A known follow-up stores the marks in the first row and first column of the matrix itself to reach O(1) space, but this lesson uses separate vectors.
Step by step
- Store the dimensions.
mis the number of rows,matrix.len(), andnis the number of columns,matrix[0].len(). All rows have the same length. - Create the marks:
zero_rowasvec![false; m]andzero_colasvec![false; n], both mutable.zero_row[i]says whether rowiheld a zero, andzero_col[j]the same for columnj. - Loop over the rows with
igoing over0..m. This first pass only reads. - Loop over the columns with
jgoing over0..n, so every cell is reached once. - Test the cell:
if matrix[i][j] == 0. - Record it: set
zero_row[i]andzero_col[j]totrue. Several zeros may share a row or column, and marking twice changes nothing. - Start the second pass with another loop of
iover0..m. - Loop over the columns again with
jover0..n. - Clear the cell: if
zero_row[i] || zero_col[j], setmatrix[i][j]to 0.
The solution in Rust
impl Solution {
fn set_zeroes(matrix: &mut Vec<Vec<i32>>) {
let m = matrix.len();
let n = matrix[0].len();
let mut zero_row = vec![false; m];
let mut zero_col = vec![false; n];
for i in 0..m {
for j in 0..n {
if matrix[i][j] == 0 {
zero_row[i] = true;
zero_col[j] = true;
}
}
}
for i in 0..m {
for j in 0..n {
if zero_row[i] || zero_col[j] {
matrix[i][j] = 0;
}
}
}
}
}
The Rust details worth a closer look:
&mut Vec<Vec<i32>>is a mutable borrow of the caller's matrix. Assigning tomatrix[i][j]changes the caller's data, so the function has no return value. The first pass only reads through the same reference, which is allowed.vec![false; m]builds a vector ofmcopies offalse. It must belet mutbecause the first pass writes into it.- Indexing with
usize. The loop variables come from the ranges0..mand0..n, wheremandnareusize, so they index vectors directly with no cast. - Bounds are checked. Every index is range-checked at run time, and an out-of-range one panics. The loops stay inside
mandn, so valid input never does.
Complexity
Time: O(m * n). Each of the two passes visits every cell once, with constant work per cell.
Space: O(m + n). The two boolean vectors have m and n entries. The matrix itself is changed in place and no copy of it is made.
Edge cases and common mistakes
- Clearing while scanning. A version that zeroes the row and column the moment it sees a zero turns
[[1, 1, 1], [1, 0, 1], [1, 1, 1]]into[[1, 0, 0], [0, 0, 0], [0, 0, 0]]: the cells it zeroed are mistaken for original zeros. On[[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]]it gives all zeros, while the correct answer keeps the 11 and 12. - Cells that only became zero. In that last example the correct answer is
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]]. The marks come from the original zeros only, so 11 and 12 stay. - No zeros. The marks all stay
falseand the matrix is unchanged:[[1, 2], [3, 4]]stays as it is. - A single zero cell.
[[0]]stays[[0]]. - One row or one column.
[[4, 5, 6]]has no zero and stays the same. In[[1], [0], [3]], the zero's row has one cell, and its column covers the whole matrix, so the result is[[0], [0], [0]]. - Zeros that already exist are not special. A value of 0 can sit anywhere, and negative values are ordinary values. Only the comparison
== 0matters. - Mixing up
mandn.zero_rowhas one entry per row,m, andzero_colone per column,n. Swapping them gives out-of-bounds panics on non-square matrices.
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]].[[1], [0], [3]]gives[[0], [0], [0]].[[1, 2], [3, 4]]gives[[1, 2], [3, 4]].
