MEDIUM NC#138 Blind #46 Math & Geometry
73. Set Matrix Zeroes
๐ Problem
Given an m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place with O(1) extra space.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use first row and first column as markers
- โ Track if first row/col needs to be zeroed separately
- โ First pass: use first row/col to mark which rows/cols need zeroing
- โ Second pass: set cells to 0 based on markers
- โ Finally zero first row/col if needed
- โ Time: O(m * n), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse first row and first column as markers
- โขTrack if first row/col needs to be zeroed separately
- โขFirst pass: use first row/col to mark which rows/cols need zeroing
Common Pitfalls
- โขSecond pass: set cells to 0 based on markers
- โขFinally zero first row/col if needed
- โขTime: O(m * n), Space: O(1)
๐งช Test Cases
Test Case 1
Not run Input:
setZeroes(matrix1); Expected:
null Test Case 2
Not run Input:
setZeroes(matrix2); Expected:
null Test Case 3
Not run Input:
setZeroes(matrix: number[][]); Expected:
Computed from hidden reference ๐ Code Editor
๐ค Output