Start learning free

LESSON 52 OF 314 · MATRIX

Set Matrix Zeroes in Scala: Mark First, Clear Later 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

    SCALA · MATRIX

    Set Matrix Zeroes in Scala, explained

    Problem overview

    The method setZeroes receives an Array[Array[Int]] with m rows and n columns and returns Unit. Wherever the matrix holds a 0, the whole row and the whole column of that cell must become 0. The change happens in place, in the matrix that was passed in.

    One rule matters: only the zeros that are in the matrix at the start count. A cell that turns into 0 during the process doesn't clear its own row and column. For this matrix:

    0 2 3 4
    5 0 7 8
    9 10 11 12
    

    the zeros in row 0, column 0 and row 1, column 1 clear rows 0 and 1 and columns 0 and 1, which gives:

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

    The 11 and 12 stay, because the zeros in column 0 and column 1 of the last row were created by the clearing, not present at the start.

    Approach: remember where the zeros are, then clear

    The tempting first attempt scans the matrix and zeroes a row and a column as soon as it meets a 0. That breaks the rule above: the new zeros look exactly like the original ones, so the scan keeps meeting them and clears more and more. On the matrix above, this approach turns every cell into 0:

    0 0 0 0
    0 0 0 0
    0 0 0 0
    

    The fix is to separate looking from changing. A first pass only records which rows and which columns contain a zero. A second pass then sets to 0 every cell whose row or column was recorded. The records need one boolean per row and one per column, so the extra space is O(m + n), and each pass visits every cell once, so the time is O(m * n). These are the bounds the lesson asks for.

    The lesson also mentions a follow-up with O(1) extra space, which stores the marks in the first row and first column of the matrix itself. It needs extra care for the zeros that are already in that row and column, and the solution below does not use it.

    Step by step

    1. Store the dimensions. m is matrix.length, the number of rows. n is matrix(0).length, the number of columns, which is the same for every row.
    2. Create the marks. zeroRow is an array of m booleans and zeroCol one of n, all false, made with Array.fill(m)(false). zeroRow(i) says whether row i has a zero, and zeroCol(j) the same for column j.
    3. Visit every row with i <- 0 until m.
    4. Visit every column of that row with j <- 0 until n. Together the two loops reach each cell once.
    5. Test the cell: if (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 it again changes nothing. This first pass only reads the matrix, so nothing has been lost when it ends.
    7. Start the second pass with another pair of loops over i and j.
    8. Clear a cell when its row or its column is marked: if (zeroRow(i) || zeroCol(j)), and inside it matrix(i)(j) = 0. That is exactly the set of cells the problem wants to become 0.

    The solution in Scala

    class Solution {
        def setZeroes(matrix: Array[Array[Int]]): Unit = {
            val m = matrix.length
            val n = matrix(0).length
            val zeroRow = Array.fill(m)(false)
            val zeroCol = Array.fill(n)(false)
            for (i <- 0 until m) {
                for (j <- 0 until n) {
                    if (matrix(i)(j) == 0) {
                        zeroRow(i) = true
                        zeroCol(j) = true
                    }
                }
            }
            for (i <- 0 until m) {
                for (j <- 0 until n) {
                    if (zeroRow(i) || zeroCol(j)) {
                        matrix(i)(j) = 0
                    }
                }
            }
        }
    }
    

    Scala details worth knowing:

    • Array.fill(m)(false). It builds an Array[Boolean] of length m with the second argument as every element. For zeroRow and zeroCol that gives all false to start with.
    • A val array can change its elements. val zeroRow fixes only the name. Writing zeroRow(i) = true is allowed, because Array is mutable.
    • Writing into the matrix changes the caller's array. Arrays are passed by reference, so matrix(i)(j) = 0 modifies the original rows, and the method needs no return value.
    • Indexing uses parentheses. matrix(i)(j) is row i, then column j. Square brackets in Scala are for type parameters, as in Array[Boolean].
    • == compares values. matrix(i)(j) == 0 compares two integers, as expected. No equals call is needed.
    • Short-circuit ||. In zeroRow(i) || zeroCol(j), the second operand isn't evaluated when the first is true. Either way the result is the same here.

    Complexity

    Time: O(m * n). The first pass reads each cell once, and the second pass writes at most each cell once. Creating the two boolean arrays costs O(m + n), which is smaller.

    Space: O(m + n). The two boolean arrays are the only storage that grows with the input. The matrix is modified in place and no copy is made.

    Edge cases and common mistakes

    • No zeros at all. [[1,2,3]] stays [[1,2,3]]: no mark is set, so the second pass changes nothing.
    • A single cell. [[0]] stays [[0]].
    • A single column. A column 1, 0, 3 becomes all zeros, since the zero's row clears one cell and its column clears the other two.
    • Two zeros in one row. In [[0,1,2,0],[3,4,5,2],[1,3,1,5]] the marks are zeroRow = true,false,false and zeroCol = true,false,false,true. Row 0 and columns 0 and 3 become 0, and the result is [[0,0,0,0],[0,4,5,0],[0,3,1,0]].
    • Clearing while scanning. The mistake described in the approach: zeroing a row and a column as soon as a 0 is found makes new zeros count, and everything ends up 0.
    • Using one pass for both jobs. Marks must be complete before the first cell is changed. That is why the lesson uses two separate loop nests.
    • Swapping m and n. zeroRow has m entries and zeroCol has n. On a non-square matrix, mixing them up throws an ArrayIndexOutOfBoundsException.

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