Set Matrix Zeroes - Problem

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

Follow up: Can you solve it using O(1) extra space?

Input & Output

Example 1 — Basic Matrix with Zero
$ Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
💡 Note: The zero at position (1,1) causes row 1 and column 1 to become all zeros
Example 2 — Multiple Zeros
$ Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
💡 Note: Zeros at (0,0) and (0,3) cause row 0, columns 0 and 3 to become zero
Example 3 — Single Row Matrix
$ Input: matrix = [[1,0,3]]
Output: [[0,0,0]]
💡 Note: Single row with a zero becomes entirely zero

Constraints

  • m == matrix.length
  • n == matrix[0].length
  • 1 ≤ m, n ≤ 200
  • -231 ≤ matrix[i][j] ≤ 231 - 1

Visualization

Tap to expand
Set Matrix Zeroes: Zero propagates to entire row and columnOriginal Matrix111101111Result Matrix101000101
Understanding the Visualization
1
Input Matrix
Original matrix with some zero elements
2
Identify Impact
Zero at (1,1) affects row 1 and column 1
3
Apply Zeros
Set entire affected row and column to zero
Key Takeaway
🎯 Key Insight: Use the matrix's first row and column as storage to achieve O(1) space complexity
Asked in
Microsoft 45 Amazon 38 Google 35 Apple 25
262.0K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen