Problem Statement

Set Matrix Zeroes

You are given a grid of numbers with m rows and n columns (a matrix). Wherever a 0 appears, you have to turn that 0's entire row and entire column into 0. And you must do it in place, meaning you change the same grid you were given instead of building a fresh copy on the side.

mediumArrayMatrixMatrixTime: O(m * n) · Space: O(1)

Signals to notice

set entire row and column to zeromatrix modificationmark then apply

Brute force first

Use to track which cells to zero — wasteful. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Use first row and first column as markers —. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on matrix=[[0,1,2,0],[3,4,5,2],[1,3,1,5]]

m=3, n=4. firstRowZero = any zero in row0 [0,1,2,0] -> True. firstColZero = any zero in col0 [0,3,1] -> True
Pass 1 (mark via i,j>=1): scan rows 1..2 cols 1..3 -> no interior zeros found, so no new markers set in row0/col0
Pass 2 (apply via i,j>=1): row0 is [0,1,2,0]. i=1: matrix[0][3]==0 -> set matrix[1][3]=0. i=2: matrix[0][3]==0 -> set matrix[2][3]=0. Grid now [[0,1,2,0],[3,4,5,0],[1,3,1,0]]
firstRowZero True -> zero entire row0: [0,0,0,0]. Grid now [[0,0,0,0],[3,4,5,0],[1,3,1,0]]
firstColZero True -> zero entire col0: rows become [0,..],[0,4,5,0],[0,3,1,0]
Return (in place): [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

What must stay true

Mark which rows and columns need zeroing, then apply — don't modify while scanning. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

firstRowZero = any zero in row 0;  firstColZero = any zero in col 0
for i in 1..m, j in 1..n: if matrix[i][j]==0: matrix[i][0]=0; matrix[0][j]=0
for i in 1..m, j in 1..n: if matrix[i][0]==0 or matrix[0][j]==0: matrix[i][j]=0
if firstRowZero: zero out entire row 0
if firstColZero: zero out entire col 0

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Modifying the matrix during the scan — newly set zeros would cascade incorrectly. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Matrix Pattern