Set Matrix Zeroes
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an m x n integer matrix, if a cell is 0, set its entire row and entire column to 0. Do it in place: the function returns nothing, and the tests check matrix after it runs.
Understand the problem
- Every
0in the original matrix wipes out its whole row and its whole column. - Zeros you write don't spread further. Only the zeros that were there at the start count.
- In place means you change
matrixitself rather than returning a new one.
Example 1
Input: Result:
1 1 1 1 0 1
1 0 1 → 0 0 0
1 1 1 1 0 1The 0 in the middle clears row 1 and column 1.
Example 2
Input: Result:
0 1 2 0 0 0 0 0
3 4 5 2 → 0 4 5 0
1 3 1 5 0 3 1 0The two zeros in row 0 clear row 0, column 0 and column 3.
Example 3
Input: [[1, 2], [3, 4]]
Result: [[1, 2], [3, 4]]No zeros, no changes.
Constraints
1 <= m, n <= 200-2^31 <= matrix[i][j] <= 2^31 - 1
Tip
O(m + n) extra space is straightforward. Can you do it with O(1)?
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
First record which rows and columns contain a zero (using the matrix's own first row and first column as the notepad), then clear those rows and columns.
The trap: zeroing while scanning
The obvious idea is "when you find a 0, clear its row and column right away". But then the scan reaches cells you just set to 0 and treats them as original zeros, clearing even more. On Example 1, the new 0 at (1, 2) would also wipe out column 2, which should stay.
So split the work into two phases: first record, then clear.
Approach 1: two sets (O(m + n) memory)
- Scan the matrix. For every
0at(r, c), addrtozeroRowsandctozeroCols. - Scan again. Set every cell to
0if its row is inzeroRowsor its column is inzeroCols.
Simple and correct. It uses up to m + n extra memory.
Approach 2: the matrix as its own notepad (O(1) memory, the reference solution)
The matrix already has a row and a column we can write notes in: its first row and first column.
matrix[0][c] = 0means "clear columnc".matrix[r][0] = 0means "clear rowr".
But writing notes there overwrites the first row and column's own values. So before anything, save two booleans: does the first row contain a 0? and does the first column contain a 0?
- Save
firstRowHasZeroandfirstColHasZero. - For every cell outside the first row and column: if it's
0, mark its row (matrix[r][0] = 0) and column (matrix[0][c] = 0). - For every cell outside the first row and column: if its row mark or column mark is
0, set it to0. - Last, clear the first row if
firstRowHasZero, and the first column iffirstColHasZero.
Step 4 must come last: clearing the first row earlier would erase the column marks before they're used.
Step by step
Example 2:
0 1 2 0
3 4 5 2
1 3 1 5| Step | What happens | Matrix |
|---|---|---|
| 1 | First row has a 0: yes. First column has a 0: yes. | (unchanged) |
| 2 | No zeros outside the first row/column, so no new marks. | (unchanged) |
| 3 | Column mark matrix[0][3] is 0, so clear (1,3) and (2,3). Other marks aren't 0. | 0 1 2 0 / 3 4 5 0 / 1 3 1 0 |
| 4 | Clear the first row, then the first column. | 0 0 0 0 / 0 4 5 0 / 0 3 1 0 |
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(m · n). A few passes over the matrix.
- Memory: O(1) for approach 2 (two booleans); O(m + n) for approach 1.
Common mistakes
- Zeroing during the first scan, so new zeros spread.
- Clearing the first row or column too early, which erases the marks.
- Forgetting to save whether the first row/column had a zero of its own. Then you can't tell an original
0there from a mark.
Going deeper
Using unused space inside the input as scratch memory is a recurring trick for "O(1) extra space" follow-ups. You'll see a similar idea in problems that mark visited numbers by flipping their sign.
Reference solution
/**
* @param {number[][]} matrix
* @return {void}
*/
export default function setZeroes(matrix) {
const rows = matrix.length
const cols = matrix[0].length
// The first row and column will hold our marks, so first save whether they had a 0 themselves.
const firstRowHasZero = matrix[0].includes(0)
const firstColHasZero = matrix.some((row) => row[0] === 0)
// Mark: a 0 at (r, c) marks row r (in column 0) and column c (in row 0).
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
if (matrix[r][c] === 0) {
matrix[r][0] = 0
matrix[0][c] = 0
}
}
}
// Clear every cell (outside the first row/column) whose row or column is marked.
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
if (matrix[r][0] === 0 || matrix[0][c] === 0) matrix[r][c] = 0
}
}
// Last: the first row and column, now that the marks in them are no longer needed.
if (firstRowHasZero) matrix[0].fill(0)
if (firstColHasZero) for (const row of matrix) row[0] = 0
}export default function setZeroes(matrix: number[][]): void {
const rows = matrix.length
const cols = matrix[0].length
// The first row and column will hold our marks, so first save whether they had a 0 themselves.
const firstRowHasZero = matrix[0].includes(0)
const firstColHasZero = matrix.some((row) => row[0] === 0)
// Mark: a 0 at (r, c) marks row r (in column 0) and column c (in row 0).
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
if (matrix[r][c] === 0) {
matrix[r][0] = 0
matrix[0][c] = 0
}
}
}
// Clear every cell (outside the first row/column) whose row or column is marked.
for (let r = 1; r < rows; r++) {
for (let c = 1; c < cols; c++) {
if (matrix[r][0] === 0 || matrix[0][c] === 0) matrix[r][c] = 0
}
}
// Last: the first row and column, now that the marks in them are no longer needed.
if (firstRowHasZero) matrix[0].fill(0)
if (firstColHasZero) for (const row of matrix) row[0] = 0
}def set_zeroes(matrix: list[list[int]]) -> None:
rows, cols = len(matrix), len(matrix[0])
# The first row and column will hold our marks, so first save whether they had a 0 themselves.
first_row_has_zero = 0 in matrix[0]
first_col_has_zero = any(row[0] == 0 for row in matrix)
# Mark: a 0 at (r, c) marks row r (in column 0) and column c (in row 0).
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0:
matrix[r][0] = 0
matrix[0][c] = 0
# Clear every cell (outside the first row/column) whose row or column is marked.
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
# Last: the first row and column, now that the marks in them are no longer needed.
if first_row_has_zero:
matrix[0] = [0] * cols
if first_col_has_zero:
for row in matrix:
row[0] = 0