Set Matrix Zeroes
MediumNeetCode 150Top Interview 150 Math & GeometryNykaaeBayProblem
You get a grid of integers. Whenever a cell holds 0, change every cell in its row and in its
column to 0.
Change the grid in place. Nothing is returned.
Constraints
- 1 ≤ rows, cols ≤ 200
- -10⁹ ≤ matrix[r][c] ≤ 10⁹
Examples: pick one to animate
Solutions
TimeO(rows · cols)
SpaceO(rows + cols)
Time: One pass finds the zeros and a second pass wipes cells, each visiting every cell once.
Space: One boolean per row and one per column.
Zeroing while scanning would create fake zeros that are not in the original grid. So scan first and only record which rows and columns contain a zero. A second pass then wipes every cell whose row or column is flagged.