15% off all plans & roadmaps Use code
See plansLeetCode 73 · Solution & editorial
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
Set Matrix Zeroes is a Array/Matrix Manipulation Patterns problem, in the Set Matrix Zeroes (In-place Marking) subpattern. The pattern covers in-place operations, hashing, prefix sums, spiral traversal, and cyclic sort
Learn the in-place marking technique to set entire rows and columns to zero efficiently without extra space.
The reference solution runs in O(m * n) time and O(1) space.
Set Matrix Zeroes has been reported in interviews at Facebook, Microsoft, Oracle, Amazon, Expedia, Bloomberg, Goldman Sachs, Apple.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Set Matrix Zeroes is a Array/Matrix Manipulation Patterns problem, in the Set Matrix Zeroes (In-place Marking) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.