Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Set Matrix Zeroes

LeetCode #73Medium
Find then zero · markers in the first row/col

Given an m x n matrix, if any element is 0 set its entire row and column to 0, modifying the matrix in place.

Asked atAmazonMicrosoftMeta
step 1 / 14
3 × 4 grid
1
1
1
1
1
0
1
1
1
1
0
1
Brute force · row & column sets
1given matrix
2zeroRows = {}, zeroCols = {}
3for each cell:
4 if it is 0: add its row, its col
5// second pass
6for each cell:
7 if row or col flagged: cell = 0
state
  • rule0 ⇒ zero its row + col

line 1If a cell is 0, its WHOLE row and WHOLE column must become 0. The trap: if you zero them as you go, the new zeros trigger more zeroing and the grid wipes out. So: first FIND, then ZERO.