Matrices
Medium

Set Matrix Zeroes

If an element is 0, set its entire row and column to 0.
Problem 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.

  1. Check if first row/col originally have zeros. Store in flags.
  2. Iterate through the rest of the matrix. If matrix[i][j] == 0, mark matrix[i][0] and matrix[0][j] as 0.
  3. Iterate again to set zeros based on markers.
  4. 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.
Unlock VisualizerPREMIUM FEATURE

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.

Start Your Premium Prep