Start learning free

LESSON 330 OF 667 · MATRIX

Set Matrix Zeroes in C++: Mark First, Clear Later in O(m * n)

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 a vector of rows. Each row is a vector 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

    C++ · MATRIX

    Set Matrix Zeroes in C++, explained

    Problem overview

    The method setZeroes receives an m x n matrix, a vector<vector<int>>, by reference. Wherever a cell holds 0, its whole row and its whole column must become 0. The function changes matrix in place and returns nothing.

    Only the zeros present at the start count. A cell that turns into 0 during the process doesn't clear its own row and column. Take this matrix:

    0 2 3 4
    5 0 7 8
    9 10 11 12
    

    Its zeros are at row 0, column 0 and at row 1, column 1. Rows 0 and 1 and columns 0 and 1 are cleared, and the result is:

    0 0 0 0
    0 0 0 0
    0 0 11 12
    

    The cells that only became 0 clear nothing more, so 11 and 12 stay. The statement asks for O(m * n) time and O(m + n) extra space.

    Approach: write down the zeros, then clear

    The natural first attempt scans the matrix and, on meeting a 0, clears its row and column right away. That fails, because the new zeros look exactly like original ones. When the scan reaches them, they clear their own rows and columns too, and the zeros spread much further than they should. On the first example, which has a single 0 in the middle of a 3 by 3 matrix of ones, this approach gives:

    1 0 0
    0 0 0
    0 0 0
    

    Only the middle row and column should be zero.

    The fix is to separate looking from changing. The first pass only reads the matrix and records which rows and which columns contain a zero. The second pass changes cells: a cell becomes 0 when its row or its column was recorded. All the decisions are made before any cell changes, so new zeros can't influence anything.

    The records need one flag per row and one per column, which is O(m + n) extra space. The statement's follow-up reaches O(1) by storing those flags in the first row and first column of the matrix itself, but this lesson uses the simpler separate flags.

    Step by step

    1. Read the dimensions. Store matrix.size() in an int named m (rows) and matrix[0].size() in an int named n (columns). Every row has the same length, so the first row tells the column count.
    2. Create the flags. zeroRow is a vector<bool> of size m and zeroCol one of size n, both filled with false. zeroRow[i] says whether row i held a zero.
    3. Loop over every cell with i from 0 to m - 1 and, inside it, j from 0 to n - 1. This first pass changes nothing in the matrix.
    4. Test matrix[i][j] == 0.
    5. Record it: set zeroRow[i] and zeroCol[j] to true. Several zeros can share a row or a column, and marking twice is harmless.
    6. Start the second pass with the same two nested loops. Every zero is recorded now, so cells can change safely.
    7. Clear the cell when zeroRow[i] || zeroCol[j] is true, by setting matrix[i][j] to 0.

    The solution in C++

    class Solution {
    public:
        void setZeroes(vector<vector<int>> &matrix) {
            int m = matrix.size();
            int n = matrix[0].size();
            vector<bool> zeroRow(m, false);
            vector<bool> zeroCol(n, false);
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (matrix[i][j] == 0) {
                        zeroRow[i] = true;
                        zeroCol[j] = true;
                    }
                }
            }
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (zeroRow[i] || zeroCol[j]) {
                        matrix[i][j] = 0;
                    }
                }
            }
        }
    };
    

    The C++ details worth knowing:

    • vector<bool>(m, false) creates m elements, all false. Writing zeroRow[i] = true only works because those elements exist already; indexing never adds elements.
    • vector<bool> is a special case. It packs the booleans into bits to save memory, so zeroRow[i] returns a small proxy object instead of a bool&. Assigning to it and reading it in a condition work as usual, which is all this solution needs. Where it matters is code that takes a real reference or address of an element, which doesn't compile for vector<bool>.
    • The matrix is passed by reference (&matrix), so the second pass changes the caller's matrix. The function returns void because the result is the changed matrix itself.
    • The values can be any int. The code only compares with 0 and assigns 0, so negative numbers and extreme values like INT_MIN and INT_MAX cause no overflow.

    Complexity

    Time is O(m * n). Each pass visits every cell once, and each visit costs O(1).

    Extra space is O(m + n). zeroRow has m flags and zeroCol has n. That matches the bound in the statement.

    Edge cases and common mistakes

    • Clearing while scanning. As shown above, writing zeros during the first pass makes them spread. Keep reading and writing in separate passes.
    • No zeros at all. Both flag vectors stay all false, and the matrix is unchanged. {{1, 2, 3}} stays {{1, 2, 3}}.
    • A 1 by 1 matrix. {{5}} stays {{5}} and {{0}} stays {{0}}.
    • A single column. {{1}, {0}, {3}} becomes {{0}, {0}, {0}}, because the zero's row is one cell and its column is the whole matrix.
    • Zeros in the first row or column. With separate flag vectors they need no special handling. They only matter in the O(1) space follow-up, where the first row and column double as the flag storage.
    • Swapping m and n. zeroRow is indexed by the row i and must have m elements, zeroCol by j with n elements. Swapped sizes go out of bounds when the matrix isn't square.

    Testing

    The 3 by 4 matrix {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}} has both zeros in row 0, in columns 0 and 3. The result is:

    0 0 0 0
    0 4 5 0
    0 3 1 0
    

    The 3 by 3 matrix of ones with one 0 in the middle becomes:

    1 0 1
    0 0 0
    1 0 1
    
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free