mediumArrayMatrixArrays & Hashing

Set Matrix Zeroes

mediumTime: O(m * n)Space: O(1)

Recognize the pattern

set entire row and column to zeromatrix modificationmark then apply

Brute force idea

The naive version of Set Matrix Zeroes sounds like this: 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.

Better approach

The real unlock in Set Matrix Zeroes comes when you notice this: 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.

Key invariant

The compass for Set Matrix Zeroes is this: 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.

Watch out for

The trap in Set Matrix Zeroes usually looks like this: 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.

Arrays & Hashing Pattern