Start learning free

LESSON 52 OF 314 · MATRIX

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

    JAVA · MATRIX

    Set Matrix Zeroes in Java, explained

    Problem overview

    The method setZeroes receives an int[][] matrix with m rows and n columns. Wherever an element is 0, the whole row and the whole column of that element 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 [[1, 1, 1], [1, 0, 1], [1, 1, 1]] the only 0 is in row 1 and column 1, so the result is [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. For [[0, 2, 3, 4], [5, 0, 7, 8], [9, 10, 11, 12]] the zeros clear rows 0 and 1 and columns 0 and 1, giving [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 11, 12]]. The 11 and 12 stay because no original zero lies in their row or column.

    Approach: remember now, clear later

    The tempting solution is to clear a row and a column the moment you meet a 0. That fails, because the zeros you write look exactly like original zeros when the scan reaches them, and they clear rows and columns that should have stayed. Running that approach on the 3 by 4 example above wipes the whole matrix to [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], not the expected result.

    The fix is to split the work into two passes:

    1. Record. Scan the matrix without changing it. For each 0, note its row and its column.
    2. Clear. Scan again. A cell becomes 0 if its row or its column was noted.

    The notes are two arrays of booleans, one entry per row and one per column. That is O(m + n) extra space, which is what the lesson asks for. Marking the same row twice does nothing, so several zeros in one row or column are no problem. The follow-up in the statement keeps the notes in the matrix's own first row and first column to reach O(1) space. That version has to handle the first row and column separately, and this lesson does not require it.

    Step by step

    1. Read the dimensions. m = matrix.length is the number of rows. n = matrix[0].length is the number of columns, because every row has the same length.
    2. Create the marks. boolean[] zeroRow has size m and boolean[] zeroCol has size n. A new boolean array is full of false, which is the right starting value: no row or column has a zero yet.
    3. First pass. Two nested loops visit every matrix[i][j]. This pass only reads the matrix.
    4. Record each zero. When matrix[i][j] == 0, set zeroRow[i] and zeroCol[j] to true.
    5. Second pass. Two more nested loops visit every cell again. All original zeros are recorded now, so changing cells loses nothing.
    6. Clear. If zeroRow[i] || zeroCol[j] is true, set matrix[i][j] = 0.

    The solution in Java

    class Solution {
        public void setZeroes(int[][] matrix) {
            int m = matrix.length;
            int n = matrix[0].length;
            boolean[] zeroRow = new boolean[m];
            boolean[] zeroCol = new boolean[n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (matrix[i][j] == 0) {
                        zeroRow[i] = true;
                        zeroCol[j] = true;
                    }
                }
            }
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (zeroRow[i] || zeroCol[j]) {
                        matrix[i][j] = 0;
                    }
                }
            }
        }
    }
    

    The Java details worth a closer look:

    • Method return type. The method is void. A Java array is an object, and the method receives a reference to the caller's array, so assigning into matrix[i][j] changes what the caller sees.
    • Default values. new boolean[m] is filled with false, as new int[m] is filled with 0, so no initialisation loop is needed.
    • Comparing with 0. matrix[i][j] == 0 compares primitive int values, so == is the right operator here.
    • Short-circuit or. In zeroRow[i] || zeroCol[j], Java skips the second test when the first is already true. Both are plain array reads, so the result is the same either way.
    • Full int range. The values can be anywhere from -2147483648 to 2147483647. The method never does arithmetic on them, only compares with 0 and assigns 0, so nothing can overflow. For [[-2147483648, 0], [4, 2147483647]] it returns [[0, 0], [4, 0]].

    Complexity

    Time: O(m * n). Each pass visits every cell once, so the method does two passes of m * n steps.

    Space: O(m + n). The two boolean arrays hold one entry per row and one per column. The matrix itself is changed in place, with no copy.

    Edge cases and common mistakes

    • Clearing while scanning. New zeros are mistaken for original ones and spread further. That is why the first pass only records.
    • No zeros. [[5]] and [[1, 2, 3]] are returned unchanged, because no mark is ever set.
    • A single zero. [[0]] stays [[0]].
    • Several zeros in one row or column. Setting a mark that is already true does no harm, so the example with two zeros in row 0, [[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]].
    • Swapping m and n. The row marks need matrix.length entries and the column marks need matrix[0].length. With a non-square matrix, mixed-up sizes cause an ArrayIndexOutOfBoundsException.
    • Using a value other than 0 as the marker. Writing a placeholder such as -1 into the matrix as a mark is not safe, since -1 is a legal value in the input. Separate boolean arrays avoid the problem.

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