Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in TypeScript: O(m + n) Marks, Two Passes

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

    TYPESCRIPT · MATRIX

    Set Matrix Zeroes in TypeScript, explained

    Problem overview

    The method setZeroes receives matrix, a number[][] with m rows and n columns. Wherever a cell holds 0, its entire row and entire column must become 0. The change happens in place and nothing is returned. Only the zeros present at the start count: a cell that becomes 0 during the process does not clear its own row and column.

    For this input:

    [0, 2, 3, 4]
    [5, 0, 7, 8]
    [9, 10, 11, 12]
    

    the matrix afterwards is:

    [0, 0, 0, 0]
    [0, 0, 0, 0]
    [0, 0, 11, 12]
    

    The zeros at (0, 0) and (1, 1) clear rows 0 and 1 and columns 0 and 1. The cells that only became 0 clear nothing more, so 11 and 12 stay.

    Approach: remember first, clear later

    The tempting way is to scan the matrix and, at each 0, zero the row and column immediately. That breaks the rule about original zeros: the new zeros are indistinguishable from the old ones, and later in the scan they would clear rows and columns that should stay. On the example above it zeroes everything, including 11 and 12.

    The fix is to split the work into two passes:

    1. Record. Scan the matrix without changing it, and note which rows and which columns contain a zero. Two boolean arrays are enough: zeroRow[i] for row i and zeroCol[j] for column j.
    2. Clear. Scan again. A cell becomes 0 if its row is marked or its column is marked.

    Several zeros can share a row or column, and marking twice changes nothing. The marks cost m + n booleans, which fits the O(m + n) extra-space limit. The follow-up in the statement, O(1) space, stores the marks in the matrix's first row and first column instead; this lesson keeps them in separate arrays.

    On the example, the first pass leaves zeroRow as [true, true, false] and zeroCol as [true, true, false, false]. The second pass clears every cell in rows 0 and 1 and in columns 0 and 1, and leaves the bottom-right two cells alone.

    Step by step

    1. Store the dimensions: m is matrix.length (the rows) and n is matrix[0].length (the columns). Every row has the same length.
    2. Create the marks: zeroRow with m values and zeroCol with n values, all false. Writing down the zeros first is what stops new zeros from being mistaken for old ones.
    3. Loop over the rows with i for the first pass. This pass only reads the matrix.
    4. Loop over the columns of row i with j, so the two loops reach each cell once.
    5. Test matrix[i][j] === 0.
    6. Mark both: set zeroRow[i] and zeroCol[j] to true.
    7. Start the second pass with another loop over the rows. Every zero is recorded now, so cells can change safely.
    8. Loop over the columns again.
    9. Clear marked cells: if zeroRow[i] || zeroCol[j], set matrix[i][j] to 0.

    The solution in TypeScript

    class Solution {
        setZeroes(matrix: number[][]): void {
            const m = matrix.length;
            const n = matrix[0].length;
            const zeroRow: boolean[] = new Array(m).fill(false);
            const zeroCol: boolean[] = new Array(n).fill(false);
            for (let i = 0; i < m; i++) {
                for (let j = 0; j < n; j++) {
                    if (matrix[i][j] === 0) {
                        zeroRow[i] = true;
                        zeroCol[j] = true;
                    }
                }
            }
            for (let i = 0; i < m; i++) {
                for (let j = 0; j < n; j++) {
                    if (zeroRow[i] || zeroCol[j]) {
                        matrix[i][j] = 0;
                    }
                }
            }
        }
    }
    

    Some TypeScript details:

    • new Array(m).fill(false) makes an array of m booleans. The annotation boolean[] documents the intent and is checked by the compiler, but it disappears when the code is compiled to JavaScript.
    • === against ==. matrix[i][j] === 0 compares without any conversion, so it matches only the number 0. With == other values such as an empty string would also equal 0, although a number[][] never holds them.
    • const still allows changes inside. zeroRow is declared const, yet zeroRow[i] = true is fine: only reassigning the variable itself is forbidden.
    • void and in-place work. Arrays are passed by reference, so the method changes the caller's rows. Nothing needs to be returned.
    • Number range. Values can be as large as 2^31 - 1, which a number holds exactly. The code only compares against 0 and assigns 0, so no arithmetic is involved.

    Complexity

    Time: O(m * n). Each of the two passes visits every cell once.

    Space: O(m + n). zeroRow has m entries and zeroCol has n. Everything else is a handful of variables.

    Edge cases and common mistakes

    • Clearing during the first scan. Zeroing the row and column at once makes new zeros spread further. On the example the matrix becomes all zeros, including the 11 and 12 that should stay.
    • No zeros. Nothing is marked, so the matrix is unchanged: [[1, 2, 3]] stays [[1, 2, 3]].
    • A single cell. [[0]] stays [[0]] and [[5]] stays [[5]].
    • Sharing one array for all marks. Building the marks as an array of arrays with new Array(m).fill([]) puts the same inner array in every slot, so a change through one index shows in all. Here the marks are flat booleans, which are copied by value, so this problem does not arise.
    • Rows and columns mixed up. m counts rows and goes with zeroRow and the first index. n counts columns and goes with zeroCol and the second index.
    • Zeros in the same row or column. A row with two zeros is marked twice, which is harmless.

    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]] stays [[1, 2, 3]].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free