Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in Rust: Row and Column Marks in O(m + n) Space

Practice O(m*n) Read the full explanation

You get a grid of integers, matrix, with m rows and n columns.

Wherever a cell is 0, set its whole row and its whole column to 0. Change matrix in place and return nothing.

Only the zeros that are there at the start count. A cell you turn into 0 doesn't clear anything more.

The grid is an array of rows. Each row is an array of integers. Rows are counted from 0 at the top, columns from 0 at the left.

 

Example 1:

Input: matrix = [
  [4, 0, 6],
  [7, 8, 9]
]
Output: [
  [0, 0, 0],
  [7, 0, 9]
]
Explanation: The 0 is in row 0, column 1.
It clears row 0 and column 1.
The 7 and the 9 stay.

Example 2:

Input: matrix = [
  [2, 5, 8],
  [0, 3, 1],
  [6, 4, 0]
]
Output: [
  [0, 5, 0],
  [0, 0, 0],
  [0, 0, 0]
]
Explanation: Two cells are 0 at the start.
The 0 in row 1, column 0 clears row 1 and column 0.
The 0 in row 2, column 2 clears row 2 and column 2.
The 5 stays. Row 0 and column 1 had no 0 at the start.
The new zeros in row 0 don't count.

Example 3:

Input: matrix = [
  [7, 2, 9, 3]
]
Output: [
  [7, 2, 9, 3]
]
Explanation: There is no 0. Nothing changes.

 

Constraints:

  • 1 to 500 rows.
  • 1 to 500 columns.
  • All rows have the same length.
  • Each value fits in a 32-bit signed integer: -231 to 231 - 1.

Note:

Your algorithm should run in O(m * n) time and use O(m + n) extra space.

Follow-up: can you do it with O(1) extra space? The first row and the first column of matrix can hold the marks for the other rows and columns.

STEP 1 OF 9
    Ctrl + Enter to check

    RUST · MATRIX

    Set Matrix Zeroes in Rust, explained

    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

    1. Store the dimensions. m is the number of rows, matrix.len(), and n is the number of columns, matrix[0].len(). All rows have the same length.
    2. Create the marks: zero_row as vec![false; m] and zero_col as vec![false; n], both mutable. zero_row[i] says whether row i held a zero, and zero_col[j] the same for column j.
    3. Loop over the rows with i going over 0..m. This first pass only reads.
    4. Loop over the columns with j going over 0..n, so every cell is reached once.
    5. Test the cell: if matrix[i][j] == 0.
    6. Record it: set zero_row[i] and zero_col[j] to true. Several zeros may share a row or column, and marking twice changes nothing.
    7. Start the second pass with another loop of i over 0..m.
    8. Loop over the columns again with j over 0..n.
    9. Clear the cell: if zero_row[i] || zero_col[j], set matrix[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 to matrix[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 of m copies of false. It must be let mut because the first pass writes into it.
    • Indexing with usize. The loop variables come from the ranges 0..m and 0..n, where m and n are usize, 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 m and n, 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 false and 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 == 0 matters.
    • Mixing up m and n. zero_row has one entry per row, m, and zero_col one 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]].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free