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.
- m == matrix.length
- n == matrix[0].length
- 1 <= m, n <= 200
- -2³¹ <= matrix[i][j] <= 2³¹ - 1
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)writes0intomatrix[i][0]andmatrix[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.
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.
Approach
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.
Two ways to solve it
Store the row and column flags inside the matrix itself.
- Two booleans: remember whether row 0 and column 0 had their own zero.
- Order: inner cells first, borders last.
Answers the follow-up.
Keep one boolean per row and one per column, fill them in a first pass, and clear in a second.
- Simple: no special case for the corner.
- Cost: up to 400 extra booleans here.
A good first answer before the follow-up.
Both are O(m · n). The marker version wins on memory by reusing cells that are going to be zeroed anyway. The steps, code and demo follow the marker version; the flag-array code comes after the demo.
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.
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".
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Zeroing rows and columns during the first scan
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
clear_row_and_column(i, j)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
if matrix[i][k] != 0:
matrix[i][k] = -1 # turn into 0 laterkeep 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
if matrix[0][0] == 0:
clear row 0 and column 0row0 = 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.
Edge cases
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]].
Complexity
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.