Matrices
Medium
Set Matrix Zeroes
If an element is 0, set its entire row and column to 0.
10 min read
Solve on LeetCodeProblem Understanding
Given an m x n integer matrix, if an element is 0, set its entire row and column to 0. You must do it in-place.
Strategy (O(1) Space)
We can use the first row and first column as markers.
- Check if first row/col originally have zeros. Store in flags.
- Iterate through the rest of the matrix. If
matrix[i][j] == 0, markmatrix[i][0]andmatrix[0][j]as 0. - Iterate again to set zeros based on markers.
- Handle first row/col separately using flags.
Use
matrix[i][0]to store row status.Use
matrix[0][j]to store col status.
Interactive Visualization
Step 1 / 1
Visualization data missing
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Strategy (O(1) Space)
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Complexity Analysis
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
