Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in Go: 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

    GO · MATRIX

    Set Matrix Zeroes in Go, explained

    Problem overview

    The function setZeroes receives an m x n matrix of integers as a [][]int. Wherever an element is 0, its entire row and its entire column must become 0. The change happens in place, and the function returns nothing. Only the zeros present at the start count: a cell that becomes 0 during the process must not clear its own row and column.

    For the matrix with rows [1, 1, 1], [1, 0, 1] and [1, 1, 1], the only zero is at row 1, column 1, so the whole middle row and the whole middle column become 0, giving [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. The budget is O(m * n) time and O(m + n) extra space.

    Approach: remember now, clear later

    The obvious attempt scans the matrix and, on meeting a zero, clears its row and column right away. That breaks the rule about original zeros: the cells just cleared look like zeros to the rest of the scan and clear more rows and columns. For the 3 by 4 matrix [[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]], that approach turns everything into 0, while the correct answer keeps 11 and 12 in the last row.

    The fix is to separate looking from changing, in two passes:

    1. The first pass only reads the matrix. For each original zero, it records that the zero's row and the zero's column must be cleared.
    2. The second pass clears every cell whose row or column was recorded.

    Two slices of booleans hold the records: zeroRow[i] says whether row i contains a zero, and zeroCol[j] says the same for column j. Together they take m + n values, which is the allowed O(m + n) extra space. Several zeros can share a row or a column, and marking it again changes nothing.

    The statement mentions a follow-up with O(1) extra space, where the first row and first column of the matrix hold the marks. This lesson uses the two slices.

    Step by step

    1. Store the sizes. m is len(matrix), the number of rows, and n is len(matrix[0]), the number of columns. Every row has the same length, so the first row tells the column count.
    2. Create the marks with make([]bool, m) and make([]bool, n). Every entry starts as false.
    3. First pass: loop over the rows i from 0 to m - 1.
    4. Loop over the columns j from 0 to n - 1. The two loops reach every cell once, and this pass changes nothing in matrix.
    5. Test matrix[i][j] == 0. At this point nothing has been modified, so every zero seen is an original one.
    6. Mark the cell's row and column: zeroRow[i] and zeroCol[j] become true.
    7. Second pass: loop over the rows again, now that every zero is recorded.
    8. Loop over the columns again, one cell at a time.
    9. Clear the cell when zeroRow[i] || zeroCol[j] is true: set matrix[i][j] to 0. A cell becomes 0 exactly when its row or its column held a zero at the start.

    The solution in Go

    func setZeroes(matrix [][]int) {
        m := len(matrix)
        n := len(matrix[0])
        zeroRow := make([]bool, m)
        zeroCol := make([]bool, n)
        for i := 0; i < m; i++ {
            for j := 0; j < n; j++ {
                if matrix[i][j] == 0 {
                    zeroRow[i] = true
                    zeroCol[j] = true
                }
            }
        }
        for i := 0; i < m; i++ {
            for j := 0; j < n; j++ {
                if zeroRow[i] || zeroCol[j] {
                    matrix[i][j] = 0
                }
            }
        }
    }
    

    The Go details worth a closer look:

    • The matrix is changed through shared rows. A [][]int is a slice of row slices. The function gets a copy of the outer slice header, but the rows are shared with the caller, so assigning matrix[i][j] = 0 changes the caller's matrix. That is why the function needs no return value.
    • make([]bool, m) creates a slice of m booleans, all false, the zero value of bool. No loop to initialise them is needed.
    • Two declarations, two lengths. m counts rows and n counts columns, so the indices are matrix[i][j] with i < m and j < n. Swapping them is a classic cause of an "index out of range" panic on a non-square matrix.
    • || short-circuits. When zeroRow[i] is true, zeroCol[j] isn't even read. The result is the same either way.

    Complexity

    Time: O(m * n). Each of the two passes visits every cell once, doing a constant amount of work per cell.

    Space: O(m + n). The two boolean slices hold m and n entries. Nothing else grows with the input.

    Edge cases and common mistakes

    • No zeros. [[1, 2], [3, 4]] stays as it is, since no mark is ever set.
    • Everything is zero already. [[0]] stays [[0]].
    • One row or one column. [[1, 2, 3]] is unchanged, and the column [[4], [0], [6]] becomes [[0], [0], [0]], because the zero's row is the middle one and its column is the only one.
    • Zeros that share a row. [[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]]. Row 0 is marked twice, which is harmless.
    • Clearing while scanning. As described in the approach, doing it in one pass lets new zeros spread. On [[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]] that gives all zeros, while the two-pass solution gives [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]].
    • Using the wrong length for the columns. Taking n from len(matrix) works only for square matrices. The column count comes from a row.

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