Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in Kotlin: O(m * n) Time with Row and Column Marks

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

    KOTLIN · MATRIX

    Set Matrix Zeroes in Kotlin, explained

    Problem overview

    Given an m x n matrix of integers as an Array<IntArray>, the function setZeroes must set the entire row and the entire column of every zero to 0. It works in place and returns nothing. Only the zeros present at the start count: a cell that becomes 0 during the work must not clear its own row and column.

    For the matrix with rows 1 1 1, 1 0 1, 1 1 1, the only zero is in row 1 and column 1, so the middle row and the middle column become zeros:

    1 0 1
    0 0 0
    1 0 1
    

    In the matrix with rows 0 2 3 4, 5 0 7 8, 9 10 11 12, the zeros at row 0, column 0 and at row 1, column 1 clear rows 0 and 1 and columns 0 and 1. The last row keeps 11 and 12:

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

    Approach

    The tempting plan is to scan the matrix and, at each zero, clear its row and column on the spot. That fails: the cells just cleared now look like zeros, and when the scan reaches them they clear their own rows and columns too. On the second example, this approach turns the whole matrix into zeros, although the last row should keep 11 and 12.

    The fix is to separate remembering from clearing. The first pass only reads the matrix and writes down which rows and columns contain a zero. The second pass then clears every cell whose row or column was marked. Because the marks are complete before any cell changes, the new zeros can't cause extra clearing.

    The marks cost O(m + n) extra space: one flag per row and one per column. The time is O(m * n), since each pass visits every cell once. The statement's follow-up shows that the first row and the first column of the matrix can hold the marks, which brings the extra space down to O(1). This lesson uses the separate flag arrays, which are simpler to get right.

    Step by step

    1. Read the dimensions. val m = matrix.size and val n = matrix[0].size. Every row has the same length, so the first row tells the number of columns.
    2. Create the marks. zeroRow is a BooleanArray(m) and zeroCol is a BooleanArray(n). They start filled with false. The flag zeroRow[i] will say whether row i has a zero, and zeroCol[j] the same for column j.
    3. First pass: loop over rows and columns. Two nested loops, i over 0 until m and j over 0 until n, reach every cell once. This pass changes nothing in the matrix.
    4. Test for a zero. if (matrix[i][j] == 0) only fires for the zeros that are really there, since nothing has changed yet.
    5. Mark. Set zeroRow[i] and zeroCol[j] to true. Several zeros can share a row or column, and marking it again changes nothing.
    6. Second pass. Another pair of nested loops over every cell. All zeros are recorded now, so cells can change safely.
    7. Clear. If zeroRow[i] || zeroCol[j], set matrix[i][j] = 0. A cell becomes zero exactly when its row or its column held a zero at the start.

    The solution in Kotlin

    class Solution {
        fun setZeroes(matrix: Array<IntArray>) {
            val m = matrix.size
            val n = matrix[0].size
            val zeroRow = BooleanArray(m)
            val zeroCol = BooleanArray(n)
            for (i in 0 until m) {
                for (j in 0 until n) {
                    if (matrix[i][j] == 0) {
                        zeroRow[i] = true
                        zeroCol[j] = true
                    }
                }
            }
            for (i in 0 until m) {
                for (j in 0 until n) {
                    if (zeroRow[i] || zeroCol[j]) {
                        matrix[i][j] = 0
                    }
                }
            }
        }
    }
    

    Kotlin details worth knowing:

    • BooleanArray(m) creates an array of m primitive booleans, all false. Likewise IntArray(n) is filled with zeros.
    • val arrays are still mutable. val zeroRow stops the name from pointing at another array, but zeroRow[i] = true changes an element, which is allowed.
    • The matrix is changed in place. The function receives the caller's row arrays, so writing matrix[i][j] = 0 changes the caller's matrix. That's why the function can return nothing.
    • || short-circuits. If zeroRow[i] is true, zeroCol[j] is not even read.
    • Full Int range. The values can be anything from Int.MIN_VALUE to Int.MAX_VALUE. The code only compares with 0 and assigns 0, so no arithmetic can overflow.

    Complexity

    Time is O(m * n): two passes over all cells. Extra space is O(m + n): the two flag arrays. The matrix is changed in place, with no copy.

    Edge cases and common mistakes

    • Clearing while scanning. As described above, clearing a row and column at the first zero spreads zeros to the whole matrix. On the matrix with rows 0 2 3 4, 5 0 7 8, 9 10 11 12, that version ends with every cell equal to 0 instead of keeping 11 and 12.
    • No zeros. Both flag arrays stay false and the matrix is untouched: rows 1 2 3 and 4 5 6 stay as they are.
    • A 1 by 1 matrix. [5] stays [5], and [0] stays [0].
    • Extreme values. The matrix with rows Int.MIN_VALUE 0 and 7 Int.MAX_VALUE becomes rows 0 0 and 7 0: the zero is in row 0 and column 1, so row 0 and column 1 are cleared and the 7 survives.
    • Assuming the first row tells the rows' count. It tells the number of columns. The number of rows is matrix.size.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free