Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in Swift: Row and Column Marks 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 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

    SWIFT · MATRIX

    Set Matrix Zeroes in Swift, explained

    Problem overview

    The method setZeroes receives a matrix as an inout [[Int]], 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 the zeros present at the start count: a cell that becomes 0 during the process must not clear its own row and column.

    In the first example, the matrix has a single 0 in the middle, at row 1, column 1. The result has a zero middle row and a zero middle column, and four 1s in the corners. The statement expects O(m * n) time and O(m + n) extra space, and mentions a follow-up with O(1) space.

    Approach: remember now, clear later

    The tempting plan is to clear the row and the column as soon as a 0 is found. It breaks because the new zeros look exactly like the original ones. On the matrix with rows [0, 2, 3, 4], [5, 0, 7, 8] and [9, 10, 11, 12], clearing at once ends with every cell 0, although the correct result keeps 11 and 12 in the last row.

    The fix is to separate looking from changing. A first pass over the matrix only records which rows and columns contain a zero. A second pass then sets a cell to 0 if its row or its column was recorded. Two arrays of Bool do the recording: zeroRow has one entry per row and zeroCol has one per column. Together they take O(m + n) space.

    For the matrix [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]], the first pass produces:

    zeroRow = [true, false, false]
    zeroCol = [true, false, false, true]
    

    The second pass clears row 0 and columns 0 and 3, and the result is [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]].

    The follow-up removes the two arrays by storing the marks in the first row and the first column of the matrix itself. That needs extra care, because those cells may hold zeros of their own. This lesson uses the two arrays.

    Step by step

    1. Store the dimensions. matrix.count is the number of rows, m, and matrix[0].count is the number of columns, n. Every row has the same length, so the first row is enough.
    2. Create the two mark arrays as var arrays of Bool, all false: zeroRow with m entries and zeroCol with n. They are written to later, so they are var.
    3. First pass, rows. Loop i over 0..<m. This pass only reads the matrix.
    4. First pass, columns. Inside it, loop j over 0..<n. Together the two loops reach every cell once.
    5. Test for a zero with matrix[i][j] == 0.
    6. Record it. Set zeroRow[i] and zeroCol[j] to true. Several zeros can share a row or a column, and marking again changes nothing.
    7. Second pass, rows and columns. Two more nested loops over i and j visit every cell again.
    8. Clear marked cells. If zeroRow[i] || zeroCol[j], set matrix[i][j] to 0. A cell becomes 0 exactly when its row or its column held a zero at the start, which is what the marks say.

    The solution in Swift

    class Solution {
        func setZeroes(_ matrix: inout [[Int]]) {
            let m = matrix.count
            let n = matrix[0].count
            var zeroRow = [Bool](repeating: false, count: m)
            var zeroCol = [Bool](repeating: false, count: n)
            for i in 0..<m {
                for j in 0..<n {
                    if matrix[i][j] == 0 {
                        zeroRow[i] = true
                        zeroCol[j] = true
                    }
                }
            }
            for i in 0..<m {
                for j in 0..<n {
                    if zeroRow[i] || zeroCol[j] {
                        matrix[i][j] = 0
                    }
                }
            }
        }
    }
    

    Swift details worth knowing:

    • inout parameters. Arrays are value types, so a normal parameter is a read-only copy. With inout, the writes to matrix reach the caller's array. The caller passes a var with &, for example solution.setZeroes(&grid).
    • [Bool](repeating: false, count: m) builds an array of m copies of false.
    • Nested subscripts. matrix[i][j] = 0 writes into the row stored inside matrix. It works because matrix is a var (an inout parameter counts as one).
    • || short-circuits. If zeroRow[i] is true, zeroCol[j] isn't read. The result is the same either way.
    • Value range. The values can be as large as 2147483647 in size, which fits easily in a 64-bit Int. The method only compares them with 0.

    Complexity

    Time: O(m * n). Each of the two passes visits every cell once, and each visit costs a constant amount of work.

    Space: O(m + n). zeroRow holds m flags and zeroCol holds n. The follow-up reaches O(1) by keeping those flags in the matrix's first row and column.

    Edge cases and common mistakes

    • Clearing while scanning. New zeros are indistinguishable from original ones and clear too much. On the matrix with rows [0, 2, 3, 4], [5, 0, 7, 8] and [9, 10, 11, 12], that approach turns everything into 0.
    • No zeros. [[5]] and [[1, 2, 3]] come back unchanged, because no flag is ever set.
    • A single zero. [[0]] stays [[0]].
    • One column. [[1], [0], [3]] becomes [[0], [0], [0]]: the zero's row is only one cell, but its column is the whole matrix.
    • Several zeros in one row or column. Example 2 has two zeros in row 0. Row 0 is marked twice, which is harmless.
    • Confusing m and n. zeroRow is indexed by row and has m entries, and zeroCol is indexed by column and has n. Swapping them gives an index error on any non-square matrix.
    • Returning something. The method has no return value. The result is the caller's matrix after the call.

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