Visualize

Pattern visualizer

Set Matrix Zeroes

Zeroing cells while you're still scanning for zeros is a trap — a zero you just wrote would look like an original zero and cascade into rows/columns that shouldn't be touched. So split it into two passes: first scan and just remember which rows and columns contain a zero, then a second pass actually writes the zeros using that record. Animated on: matrix = [[1,1,1],[1,0,1],[1,1,1]] — if a cell is 0, zero its entire row and column (shown flattened row-major, index = row*3+col; the single 0 is at idx4, row1 col1)..

Record first, zero second

time O(rows * cols)space O(1) extrastep 1 / 8
1
[0]
1
[1]
1
[2]
1
[3]
0
[4]
1
[5]
1
[6]
1
[7]
1
[8]
line 4

First pass: scan for zeros, remembering which rows/cols they're in — without zeroing yet, to avoid cascading.

Pseudocode
1FUNCTION setZeroes(matrix):
2 make an empty set of zero-rows and an empty set of zero-cols
3 FOR each cell (r,c):
4 IF matrix[r][c] is 0: add r to zero-rows and add c to zero-cols
5 FOR each cell (r,c):
6 IF r is in zero-rows or c is in zero-cols: set matrix[r][c] = 0

← / → step · space play · Home restart

Where to practice Matrix