Browse Curriculum
FAANGPrep Sprint
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

Watch how we use the first row and column as makers to avoid using O(MN) extra space.

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.