Algorithms · Visualized
Matrix: Set Matrix Zeroes
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
If any cell in a matrix is 0, its entire row and column must be set to 0. Time: O(rows × cols) average, O(rows × cols) worst; space: O(1) — using the matrix itself as marker storage, instead of O(rows + cols) extra arrays.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Set Matrix Zeroes
Matrix / 2D ArrayIf any cell in a matrix is 0, its entire row and column must be set to 0. Doing this naively risks zeroing out cells that then incorrectly trigger more zeroing. The efficient trick: use the matrix's own first row and first column as 'markers' to remember which rows/columns need zeroing, avoiding extra memory.
How Set Matrix Zeroes Works
- First, check separately whether the original first row and first column contain any zeros (remember this in two flags), since they'll be reused as marker space.
- Scan the rest of the matrix (excluding row 0 and column 0): whenever you find a 0 at position (i, j), mark it by setting the cell at (i, 0) and (0, j) to 0 — using row 0 and column 0 as marker space.
- Scan the matrix again (excluding row 0 and column 0): for each cell, check if its row marker (column 0) or column marker (row 0) is 0, and if so, set that cell to 0.
- Finally, using the two flags saved in step 1, zero out row 0 entirely if it originally had a zero, and zero out column 0 entirely if it originally had a zero.
- The matrix now correctly has every affected row and column zeroed, using no extra matrix.
Set Matrix Zeroes Worked Example
Input: [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Found a 0 at (1,1). Mark row0 col1 and row1 col0 as 0 (markers): [[1,0,1],[0,0,1],[1,1,1]]. Second pass: cell(0,0) unaffected (its own markers are non-zero at this stage)... Actually row1's marker (row1,col0=0) zeroes the whole row1; column1's marker (row0,col1=0) zeroes the whole column1. Final matrix: [[1,0,1],[0,0,0],[1,0,1]].
def set_zeroes(m):
rows, cols = set(), set()
for r in range(len(m)):
for c in range(len(m[0])):
if m[r][c] == 0:
rows.add(r)
cols.add(c)
for r in rows:
for c in range(len(m[0])):
m[r][c] = 0
for c in cols:
for r in range(len(m)):
m[r][c] = 0
return mBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Set Matrix Zeroes Time & Space Complexity
When to Use Set Matrix Zeroes
- Spreadsheet-style data invalidation: propagating a 'zero out' rule to whole rows/columns based on a trigger cell.
- A classic space-optimization exercise, showing how to reuse existing structure instead of allocating new memory.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.