DSA AnimatorREVISION VIDEOS
← Back to problems
New

Set Matrix Zeroes — LeetCode 73 video explanation

If a cell is 0, set its entire row and column to 0. Do it in place.

Loading videos…

DSA Animator › DSA Revision › Matrix › Set Matrix Zeroes

Key moments in the Set Matrix Zeroes video

0:03Problem0:09Example0:18Brute force0:28Key idea0:43Dry run1:07Code1:28Takeaway

What you will learn

Remember: mark first, apply later, so new zeros do not spread. The first row and column can store the marks for free. The video solves Set Matrix Zeroes (LeetCode 73, Medium) with the In-place Markers pattern from the Matrix topic, and you can replay every step in the interactive Set Matrix Zeroes animation.

Set Matrix Zeroes video transcript

Problem

If a cell is 0, set its entire row and column to 0. Do it in place.

Example

In this 3 by 4 matrix, the zeros sit in row 0, at columns 0 and 3. So row 0, column 0 and column 3 all become 0.

Brute force

Zeroing rows and columns while you scan is wrong, because the new zeros would trigger more zeros. Copying the matrix fixes that, but costs O of m times n space.

Key idea

First record which rows and columns must become zero, then apply it. To use constant space, store those marks in the first row and the first column themselves. Two extra flags remember whether the first row and first column had a zero of their own.

Dry run

The first row has a zero, so its flag is true. The first column also has a zero, so its flag is true. The zero in the first row at column 3 already marks column 3. Now every inner cell in a marked column becomes 0: so rows 1 and 2 at column 3 become 0. Finally the flags zero the whole first row and the whole first column. The result keeps only 4, 5, 3 and 1 in the middle.

Code

In code, first check the first row and first column for zeros, and save two flags. Then for every inner zero, mark its row in column 0 and its column in row 0. Zero every inner cell whose row or column is marked. Last, use the flags to zero the first row and first column. That's O of m times n time and O of 1 extra space.

Takeaway

Remember: mark first, apply later, so new zeros do not spread. The first row and column can store the marks for free.

More Matrix revision videos

← All 185 DSA revision videos