Set Matrix Zeroes

Turn every row and column that holds a 0 into zeros, using the matrix itself to remember which ones to clear.

Given a grid of integers matrix with m rows and n columns, find every cell that holds 0 and set its whole row and whole column to 0. Change matrix itself, in place, rather than returning a new grid. As a further challenge, use only a fixed amount of extra memory, however large the grid is.

Example 1
Input: matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output: [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Example 2
Input: matrix = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]
Output: [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
Solution

The Idea

Think of a scorecard where a 0 in any cell cancels everything in its line, both across and down. Rows and columns are counted from 0, with row 0 at the top and column 0 (col 0 for short) on the left. In Example 1 the single 0 sits at row 1, col 1. So all of row 1 and all of col 1 become 0, and the four corner cells keep their 1.

The obvious plan is to scan the cells from the top left and clear a row and a column the moment a 0 turns up. Try it on Example 1. At row 1, col 1 the scan clears row 1 and col 1. The very next cell, row 1, col 2, now holds 0, so the scan clears col 2 as well. The zeros keep spreading, and the grid ends as [[1, 0, 0], [0, 0, 0], [0, 0, 0]] instead of the expected output.

The trouble is that a 0 written by the scan looks exactly like a 0 that was there from the start. So how can we remember which rows and columns to clear without confusing our own zeros with the real ones? Finish reading first, keep a record, and clear only afterwards. The record needs one tick for each row and one tick for each column.

The grid itself already has room for that record. Row 0 has one cell above every column, and col 0 has one cell beside every row. A 0 at row i, col j can leave its marks there: a 0 in row i, col 0 means "clear row i", and a 0 in row 0, col j means "clear col j".

Example 1 in three stages. At the start the one 0 is at row 1, col 1. After marking, row 1, col 0 and row 0, col 1 hold 0 as marks. After clearing, row 1, col 2 and row 2, col 1 are cleared because their row or column is marked.

The panel labelled "start" shows the original 0 in blue, at row 1, col 1. In "after marking", that 0 has left two orange marks: one at row 1, col 0 for its row, and one at row 0, col 1 for its column. In "after clearing", every other cell has looked at the mark at the left end of its row and the mark at the top of its column. The two teal cells, row 1, col 2 and row 2, col 1, had a mark and became 0. The corners had none and kept their 1.

So the matrix carries its own to-do list in its top row and left column. The one catch is that those cells can hold real zeros of their own, as row 0 of Example 2 does.

Solution Approach

The code rests on four choices: a simple record in two extra arrays and its cost, moving that record into row 0 and col 0, keeping their own zeros apart from the marks, and the order of clearing.

Recording first, with two arrays

What is the simplest record that works? Two boolean arrays, one with m entries for the rows and one with n entries for the columns. One pass over the grid ticks the row and column of every 0, and a second pass sets a cell to 0 when its row or column is ticked. That is correct, but it needs m + n extra booleans, which grows with the grid.

Marks in row 0 and col 0

How can the grid hold the ticks instead? For every 0 at row i, col j, with both i and j at least 1, write 0 into row i, col 0 and into row 0, col j. Writing 0 over a cell in the top row or left column loses nothing that matters. That row or column is being cleared anyway, because the 0 at row i, col j shares it.

The real zeros of row 0 and col 0

What about a 0 that was in row 0 or col 0 from the start? Look at Example 2. Row 0 is [0, 1, 2, 0], so the whole of row 0 must be cleared. Once marks are written, though, a 0 in row 0 could mean "clear this column" or "row 0 itself had a 0", and the two cannot be told apart.

The fix is to read row 0 and col 0 before any mark exists, and keep the answers in two booleans. Here they are named firstRowZero and firstColZero. In Example 2 both are true, because the 0 at row 0, col 0 lies in both.

Why not let the corner cell, row 0, col 0, stand for both? Take [[1, 1], [0, 1]]. Its 0 at row 1, col 0 means col 0 must be cleared, but row 0 must keep its 1 at col 1. If a 0 in the corner meant "clear row 0 and col 0", that 0 would also wipe row 0, and the result would be [[0, 0], [0, 0]].

The order of clearing

Which cells get cleared first? The inner cells, those with row and column at least 1, go first, because they read their marks from row 0 and col 0. Row 0 and col 0 are cleared last. In Example 2, row 0 must be cleared, and clearing it early would turn every cell in it into 0. Every column would then look marked, and the whole grid would end up as zeros.

Java Solution

The method setZeroes changes matrix in these steps:

  1. First, store the number of rows in m and the number of columns in n. One loop reads row 0 and sets firstRowZero if it holds a 0, and a second loop does the same for col 0 with firstColZero.
  2. Then visit the inner cells with two loops, one inside the other: the outer loop moves i over rows 1 to m - 1, and the inner loop moves j over columns 1 to n - 1. For each 0 found, set matrix[i][0] and matrix[0][j] to 0 as marks.
  3. Visit the same inner cells again with a second pair of loops. Set a cell to 0 when the mark for its row, matrix[i][0], or the mark for its column, matrix[0][j], is 0.
  4. Finally, if firstRowZero is true, set all of row 0 to 0, and if firstColZero is true, set all of col 0 to 0. Nothing is returned: the caller sees the answer in matrix itself.

A small helper, run, calls setZeroes and prints the grid row by row. The main method uses it on both examples, on [[1, 1], [0, 1]] whose only 0 is in col 0, on a grid with a single column, and on a grid with no zeros.

Java
public class SetMatrixZeroes {

    public static void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        boolean firstRowZero = false;
        boolean firstColZero = false;
        for (int j = 0; j < n; j++) {
            firstRowZero |= matrix[0][j] == 0;
        }
        for (int i = 0; i < m; i++) {
            firstColZero |= matrix[i][0] == 0;
        }
        // Use row 0 and column 0 as marks for the rest of the matrix.
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;     // mark row i
                    matrix[0][j] = 0;     // mark column j
                }
            }
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (firstRowZero) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
        if (firstColZero) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
    }

    static void run(String name, int[][] matrix) {
        setZeroes(matrix);
        System.out.println(name + ":");
        for (int[] row : matrix) {
            System.out.println("  " + java.util.Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        run("Example 1", new int[][] {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}});
        run("Example 2", new int[][] {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}});
        run("Zero in column 0 only", new int[][] {{1, 1}, {0, 1}});
        run("One column", new int[][] {{1}, {0}, {1}});
        run("No zeros", new int[][] {{1, 2}, {3, 4}});
    }
}

Running it prints:

Output
Example 1:
  [1, 0, 1]
  [0, 0, 0]
  [1, 0, 1]
Example 2:
  [0, 0, 0, 0]
  [0, 4, 5, 0]
  [0, 3, 1, 0]
Zero in column 0 only:
  [0, 1]
  [0, 0]
One column:
  [0]
  [0]
  [0]
No zeros:
  [1, 2]
  [3, 4]

Under "Example 1", the corner cells still hold 1 in [1, 0, 1], both at the top and at the bottom. Clearing as soon as a 0 is found gave [[1, 0, 0], [0, 0, 0], [0, 0, 0]] on the same input. Under "Example 2", row 0 and col 0 are all zeros thanks to the two booleans, and col 3 is cleared by its mark in row 0. The values 4, 5, 3 and 1 survive.

Under "Zero in column 0 only", the first line is [0, 1]: col 0 was cleared, but the 1 at row 0, col 1 was kept. Letting the corner cell stand for both row 0 and col 0 turns this grid into [[0, 0], [0, 0]] instead. The single column becomes all zeros through firstColZero alone, since it has no inner cells, and the grid with no zeros comes back as [1, 2] and [3, 4], untouched.

Complexity

A few passes over the grid do the job, and the record lives in the grid itself.

  • Time: O(m × n), because the marking pass and the clearing pass each visit the inner cells once, and reading and clearing row 0 and col 0 add at most m + n steps each.
  • Space: O(1), because the marks sit in row 0 and col 0 of matrix, so the only extra memory is two booleans and the loop counters, not the m + n booleans of the two-array record.

Storing notes inside the input array also solves Find All Numbers Disappeared in an Array.