DSA AnimatorDSA animations
Set Matrix Zeroes LC #73 Medium In-Place Markers · O(1) Space
Problem

Given an m × n integer matrix, if an element is 0, set its entire row and column to 0. You must do it in place.

Example 1
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Explanation: Zero at (1,1) zeroes entire row 1 and col 1.
Example 2
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Explanation: Zeros at (0,0) and (0,3) zero their rows and cols.
Constraints: 1 ≤ m, n ≤ 200  |  −2³¹ ≤ matrix[i][j] ≤ 2³¹ − 1
Try Examples
Custom:
Matrix Grid
⏳ Ready Select an example to begin.
Original zero
Row marker (first col)
Col marker (first row)
Being zeroed
Final zero
Variables
Phase
—
r
—
c
—
firstRowZero
—
firstColZero
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Check if row 0 / col 0 originally contain a zero → firstRowZero, firstColZero
2
Mark pass (r,c ≥ 1): if mat[r][c]==0 set mat[r][0]=0 and mat[0][c]=0
3
Zero pass (r,c ≥ 1): if mat[r][0]==0 or mat[0][c]==0 → set mat[r][c]=0
4
Fix row 0 if firstRowZero, fix col 0 if firstColZero
Time
O(m×n)
Space
O(1)
Why O(1) Space?

We repurpose the first row and first column as flag arrays — they already exist in the matrix, so no extra storage is needed. The only catch: before we overwrite them with markers, we must remember whether they themselves originally contained zeros (stored in firstRowZero and firstColZero). Then we mark, zero, and finally fix those edge rows/cols.

How to solve Set Matrix Zeroes

LeetCode 73 · Medium · Matrix · Pattern: In-place Markers

Why the obvious approach is slow

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(m) times n space.

The 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.

Remember

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

Run the animation above on your own input, or watch the 1:37 video explanation of Set Matrix Zeroes with a dry run and Java code.

More Matrix problems