Set Matrix Zeroes
If a cell is 0, zero its row and column — mark in-place with first row/col flags, O(1) extra space.
intermediate3 min read
- dsa
- arrays
- interview
- Meta
- Amazon
- Microsoft
The problem
Given an m × n integer matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Input:
[[1,1,1],
[1,0,1],
[1,1,1]]
Output:
[[1,0,1],
[0,0,0],
[1,0,1]]
Brute force
Copy matrix; whenever original is 0, zero row/col in copy. O(mn) space.
Or: first pass record all zero positions, second pass zero rows/cols. O(m+n) or O(k) space.
function setZeroesExtra(matrix: number[][]): void {
const rows = matrix.length;
const cols = matrix[0].length;
const zr = new Set<number>();
const zc = new Set<number>();
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (matrix[r][c] === 0) {
zr.add(r);
zc.add(c);
}
}
}
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (zr.has(r) || zc.has(c)) matrix[r][c] = 0;
}
}
}
| Time | O(m · n) |
| Space | O(m + n) |
Optimal: use first row and first column as markers
- Track whether first row / first col originally contain a zero.
- For
r≥1, c≥1, ifmatrix[r][c]==0, setmatrix[r][0]=0andmatrix[0][c]=0. - Zero cells based on markers.
- Finally zero first row/col using the flags.
function setZeroes(matrix: number[][]): void {
const rows = matrix.length;
const cols = matrix[0].length;
let firstRow = false;
let firstCol = false;
for (let c = 0; c < cols; c++) if (matrix[0][c] === 0) firstRow = true;
for (let r = 0; r < rows; r++) if (matrix[r][0] === 0) firstCol = true;
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;
}
}
}
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;
}
}
if (firstRow) for (let c = 0; c < cols; c++) matrix[0][c] = 0;
if (firstCol) for (let r = 0; r < rows; r++) matrix[r][0] = 0;
}
| Time | O(m · n) |
| Space | O(1) |
Edge cases
- Zero only in first row/col
- Entire matrix becomes zero
- No zeros — unchanged
- Single row or single column
Common bugs
- Zeroing first row early and destroying markers
- Forgetting separate firstRow/firstCol flags
- Using a sentinel like
nullin a number matrix without care
Interview delivery
- O(m+n) sets is acceptable mid-level.
- Push O(1): marker row/col.
- Order of zeroing matters.
- Complexity O(mn)/O(1).