Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in C#: Mark First, Clear Later

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

    C# · MATRIX

    Set Matrix Zeroes in C#, explained

    Problem overview

    The method SetZeroes receives an int[][] matrix 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 zeros that are in the matrix at the start count: a cell that becomes 0 during the process does not clear its own row and column.

    For {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}} the only zero is in row 1, column 1, so the middle row and the middle column become 0, giving {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}. The method should run in O(m * n) time and use O(m + n) extra space.

    Approach: remember now, clear later

    The tempting plan is to scan the matrix and zero a row and a column the moment a 0 is found. That breaks the rule above. The new zeros look exactly like original ones, so a later scan would clear rows and columns that should have stayed. In {{0, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}}, the cells 11 and 12 must survive, but zeroing eagerly would turn row 2 into zeros as well.

    The fix is to split the work into two passes:

    1. A read-only pass that records which rows and which columns contain a zero.
    2. A write pass that zeroes every cell whose row or column was recorded.

    Two boolean arrays hold the records: one entry per row and one per column. That is m + n flags, which meets the O(m + n) space limit. Several zeros can share a row or column, and flagging it again changes nothing.

    The follow-up asks for O(1) extra space. The idea there is to keep the flags inside the matrix itself, in its first row and first column, which then need separate handling. This lesson uses the straightforward flag arrays.

    As a small check, take the matrix {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}}. The first pass finds zeros at row 0, column 0 and row 0, column 3, so only zeroRow[0], zeroCol[0] and zeroCol[3] are true. The second pass then clears row 0 and columns 0 and 3, and leaves the middle values 4, 5, 3 and 1 alone.

    The follow-up has one catch worth knowing. If the first row and first column store the marks for the others, a zero that was already in the first row or column would be confused with a mark. So the constant-space version first records, in two extra variables, whether the first row and the first column contained a zero themselves, and clears them last.

    Step by step

    1. Store the dimensions: m = matrix.Length rows and n = matrix[0].Length columns. Every row has the same length, so the first row gives the column count.
    2. Create zeroRow (size m) and zeroCol (size n). A new bool[] starts with every element false, which means "no zero seen yet".
    3. First pass. Two nested loops visit every cell. When matrix[i][j] == 0, set zeroRow[i] and zeroCol[j] to true. This pass changes nothing in matrix.
    4. Second pass. Two more nested loops visit every cell again. If zeroRow[i] || zeroCol[j], set matrix[i][j] to 0.

    The solution in C#

    class Solution {
        public void SetZeroes(int[][] matrix) {
            int m = matrix.Length;
            int n = matrix[0].Length;
            bool[] zeroRow = new bool[m];
            bool[] zeroCol = new bool[n];
            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;
                    }
                }
            }
        }
    }
    

    C# details worth knowing:

    • Default values. Arrays of bool are filled with false and arrays of int with 0 when created, so no initialization loop is needed.
    • Jagged array. int[][] is an array of row arrays. The row count is matrix.Length and the column count is matrix[0].Length. Cells are read as matrix[i][j]. A rectangular int[,] would use GetLength(0) and GetLength(1) instead.
    • void and in-place work. Arrays are reference types, so the caller's matrix sees every assignment made through matrix[i][j] = 0.
    • Both dimensions come from the data. A matrix with 2 rows and 2 columns has matrix.Length equal to 2 and matrix[0].Length equal to 2, so it is easy to mix the two up on square inputs. Taking n from matrix[0].Length keeps the code correct for any rectangle.
    • The test is == 0 only. Any other value, positive or negative, is not a zero, so the first pass ignores it. The second pass overwrites cells with 0 whatever they held.

    Complexity

    Time: O(m * n). Each pass visits every cell once.

    Space: O(m + n). The two flag arrays hold m and n booleans. The matrix itself is changed in place, with no copy.

    Edge cases and common mistakes

    • No zeros. {{1, 2}, {3, 4}} stays as it is, because no flag is ever set.
    • A single cell. {{0}} stays {{0}}.
    • Zeros in the first row or column. {{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}}. The flag arrays make this case need no special code.
    • Zeros created along the way. {{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}}. The cells 11 and 12 stay because only the original zeros were recorded.
    • Zeroing during the first pass. This is the classic mistake: new zeros get mistaken for original ones and clear too much.
    • Swapping m and n. A non-square matrix then indexes outside an array and throws IndexOutOfRangeException.

    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, 2}, {3, 4}} is unchanged.
    • {{0}} is unchanged.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free