LeetCode #73 Medium

Set Matrix Zeroes

Set Matrix Zeroes is LeetCode 73 (Medium). You get an m × n integer matrix. Wherever a cell holds 0, set every cell in that cell's row and column to 0.

  • Change the matrix in place; nothing is returned.
  • Only zeros that were in the original matrix count. A zero you write must not clear more rows.

The follow-up asks for constant extra space, which rules out copying the matrix or keeping one flag per row and column.

Constraints
  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -2³¹ <= matrix[i][j] <= 2³¹ - 1
arraymatrixhash-table
Open on LeetCode ↗
02

Intuition

You must know which rows and columns had a zero before you start writing zeros, and that list needs somewhere to live. The first row and the first column can hold it.

  • Markers: a zero at (i, j) writes 0 into matrix[i][0] and matrix[0][j]. Those cells are about to become 0 anyway, so nothing still needed is lost.
  • Two flags: cell (0, 0) sits in both the first row and the first column, so it cannot say which one had its own zero. Two booleans, recorded before any marking, answer that.
  • Order: fill the inner cells from the markers first, and clear the first row and column last, so no marker is erased before it is read.
How to spot this pattern

An in-place grid change where a written value looks exactly like the input that triggers the change. The fix is to finish detecting before you start writing, and to store the detection results in cells that are going to be overwritten anyway.

03

Approach

Try it first

Before reading on, try the 3 × 3 grid with a single 0 in the middle and zero rows as you scan. Watch what happens when the scan reaches a zero you wrote yourself. Then decide where 3 row flags and 3 column flags could be kept without a new array.

1

Record whether the first row and column had a zero

Set row0 if any cell of row 0 is 0 and col0 if any cell of column 0 is 0. These two cells' own information is about to be mixed with the markers, so it has to be saved first.

2

Mark from the inner cells

Scan cells with i ≥ 1 and j ≥ 1. For each 0, set matrix[i][0] = 0 and matrix[0][j] = 0. A 0 at the start of a row or column now means "clear this line".

3

Fill the inner cells from the markers

Scan the same inner cells again and set matrix[i][j] = 0 when its row marker or its column marker is 0. The markers are not touched in this pass, so every cell reads the true list.

4

Clear the first row and column last

If row0 is set, zero all of row 0; if col0 is set, zero all of column 0. Doing this earlier would turn every marker in that line into 0 and wipe out rows or columns that should have stayed.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def setZeroes(self, matrix):
▶3 m, n = len(matrix), len(matrix[0])
▶4 row0 = any(v == 0 for v in matrix[0])
▶5 col0 = any(row[0] == 0 for row in matrix)
▶6 for i in range(1, m):
▶7 for j in range(1, n):
▶8 if matrix[i][j] == 0:
▶9 matrix[i][0] = 0
▶10 matrix[0][j] = 0
▶11 for i in range(1, m):
▶12 for j in range(1, n):
▶13 if matrix[i][0] == 0 or matrix[0][j] == 0:
▶14 matrix[i][j] = 0
▶15 if row0:
▶16 for j in range(n):
▶17 matrix[0][j] = 0
▶18 if col0:
▶19 for i in range(m):
▶20 matrix[i][0] = 0
marker row and columncol 0col 1col 2011111012111row 0 had a 0?col 0 had a 0?a 3 × 3 matrix; zeros are red
matrix[[1,1,1],[1,0,1],[1,1,1]]
The shaded first row and first column will hold the markers: a 0 at the start of a row or column will mean "clear this line". Before anything is written there, their own zeros must be remembered.
marker row and columncol 0col 1col 2011111012111row 0 had a 0nocol 0 had a 0norow 0 has no 0, column 0 has no 0
row0no
col0no
Two booleans save what row 0 and column 0 held originally. Cell (0, 0) belongs to both lines, so on its own it could not say which one had the zero.
marker row and columncol 0col 1col 2010110012111row 0 had a 0nocol 0 had a 0no(1, 1) is 0 → mark row 1 and column 1
cell(1, 1)value 0
markers(1, 0) and (0, 1)set to 0
A zero here means row 1 and column 1 must be cleared. Writing 0 into (1, 0) and (0, 1) records that. Both cells are going to be 0 at the end anyway, so their old values are not needed.
marker row and columncol 0col 1col 2010110012111row 0 had a 0nocol 0 had a 0no(1, 2) is 1 → nothing to mark
cell(1, 2)value 1
This cell is not 0, so it does not ask for any row or column to be cleared.
marker row and columncol 0col 1col 2010110012111row 0 had a 0nocol 0 had a 0no(2, 1) is 1 → nothing to mark
cell(2, 1)value 1
This cell is not 0, so it does not ask for any row or column to be cleared.
marker row and columncol 0col 1col 2010110012111row 0 had a 0nocol 0 had a 0no(2, 2) is 1 → nothing to mark
cell(2, 2)value 1
This cell is not 0, so it does not ask for any row or column to be cleared.
marker row and columncol 0col 1col 2010110012111row 0 had a 0nocol 0 had a 0norow 1 and column 1 are marked → (1, 1) becomes 0
row marker0(1, 0)
column marker0(0, 1)
cell0 → 0
The dashed rings show the two markers this cell reads. At least one is 0, so the cell lies on a line that had a zero and is set to 0. The markers themselves are not changed in this pass.
marker row and columncol 0col 1col 2010110002111row 0 had a 0nocol 0 had a 0norow 1 is marked → (1, 2) becomes 0
row marker0(1, 0)
column marker1(0, 2)
cell1 → 0
The dashed rings show the two markers this cell reads. At least one is 0, so the cell lies on a line that had a zero and is set to 0. The markers themselves are not changed in this pass.
marker row and columncol 0col 1col 2010110002101row 0 had a 0nocol 0 had a 0nocolumn 1 is marked → (2, 1) becomes 0
row marker1(2, 0)
column marker0(0, 1)
cell1 → 0
The dashed rings show the two markers this cell reads. At least one is 0, so the cell lies on a line that had a zero and is set to 0. The markers themselves are not changed in this pass.
marker row and columncol 0col 1col 2010110002101row 0 had a 0nocol 0 had a 0noneither line is marked → (2, 2) keeps 1
row marker1(2, 0)
column marker1(0, 2)
Neither marker is 0, so no zero shares this cell's row or column. It keeps its value.
marker row and columncol 0col 1col 2010110002101row 0 had a 0nocol 0 had a 0norow 0 had no 0 → leave it
row0no
Row 0 had no zero of its own. Any zeros in it now are markers, and they are correct: those columns were cleared.
marker row and columncol 0col 1col 2010110002101row 0 had a 0nocol 0 had a 0nocolumn 0 had no 0 → leave it
col0no
Column 0 had no zero of its own, so only its marker cells are 0, and those rows really were cleared.
marker row and columncol 0col 1col 2010110002101row 0 had a 0nocol 0 had a 0nodone: every line with an original 0 is cleared
matrix[[1,0,1],[0,0,0],[1,0,1]]
Every row and column that held an original zero is now all zeros, and every other cell kept its value. The only extra memory was the two flags.
05

Separate row and column flags

The first pass records which rows and columns contain a zero, without changing the matrix. The second pass clears any cell whose row or column was recorded.

▶1class Solution:
▶2 def setZeroes(self, matrix):
▶3 m, n = len(matrix), len(matrix[0])
▶4 zero_row = [False] * m
▶5 zero_col = [False] * n
▶6 for i in range(m):
▶7 for j in range(n):
▶8 if matrix[i][j] == 0:
▶9 zero_row[i] = True
▶10 zero_col[j] = True
▶11 for i in range(m):
▶12 for j in range(n):
▶13 if zero_row[i] or zero_col[j]:
▶14 matrix[i][j] = 0
06

Common pitfalls

Zeroing rows and columns during the first scan

✗ Wrong
for i in range(m):
    for j in range(n):
        if matrix[i][j] == 0:
            clear_row_and_column(i, j)
✓ Right
mark every zero first,
then clear rows and columns in a second pass

The zeros you write look like original zeros, so the scan keeps finding new ones. On [[1,1,1],[1,0,1],[1,1,1]] the answer should keep the four corners as 1, but the cascade turns the whole grid into 0.

Marking a cell as cleared with -1

✗ Wrong
if matrix[i][k] != 0:
    matrix[i][k] = -1  # turn into 0 later
✓ Right
keep the marks in the first row and column, or in separate flags

This brute force assumes -1 never appears, but values range over every 32-bit integer. On [[-1,1],[1,0]] the original -1 is turned into 0 at the end, and the expected [[-1,0],[0,0]] comes back as all zeros.

Using cell (0, 0) for both the first row and the first column

✗ Wrong
if matrix[0][0] == 0:
    clear row 0 and column 0
✓ Right
row0 = any(v == 0 for v in matrix[0])
col0 = any(row[0] == 0 for row in matrix)

A zero in row 0 also writes a marker into (0, 0), which then looks like a column-0 zero too. On [[1,0],[1,1]] the answer is [[0,0],[1,0]], but trusting (0, 0) also clears column 0 and returns all zeros.

07

Edge cases

A single row or a single column

There are no inner cells, so both inner loops do nothing and the two flags do all the work. [[1,0,3]] becomes [[0,0,0]].

08

Complexity

Time
O(m · n)
Space
O(1) extra
Every cell is read a constant number of times: once for the flags or markers and once in the fill pass. The only extra memory is the two booleans.
09

Set Matrix Zeroes FAQ

Can the marking pass also start at row 0 and column 0?

It does not need to. A zero in row 0 or column 0 is already recorded by row0 or col0, and it already sits in the marker line. Starting the inner loops at 1 keeps the marker cells from being read as ordinary cells before the fill pass.

Is there a version with only one extra flag?

Yes. Let (0, 0) stand for row 0 only and keep one boolean for column 0. The fill pass must then run from the bottom-right corner back to the top, so row 0 and column 0 are overwritten only after every other cell has read them.