Set Matrix Zeroes - Problem
Set Matrix Zeroes is a classic matrix manipulation problem that tests your ability to modify data structures in place efficiently.
Given an
Key Requirements:
• Modify the original matrix directly (in-place)
• When you find a zero, mark its entire row and column to become zero
• Preserve the original zero positions while processing
Example: If you have a 3x3 matrix and position (1,1) contains zero, then row 1 and column 1 should become all zeros in the final result.
Given an
m x n integer matrix, your task is to identify all cells containing zero and then set the entire row and column of each zero cell to zero. The challenge is that you must perform this transformation in place without using extra space for a copy of the matrix.Key Requirements:
• Modify the original matrix directly (in-place)
• When you find a zero, mark its entire row and column to become zero
• Preserve the original zero positions while processing
Example: If you have a 3x3 matrix and position (1,1) contains zero, then row 1 and column 1 should become all zeros in the final result.
Input & Output
example_1.py — Basic 3x3 Matrix
$
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 the entire row 1 and column 1 to be set to zero. Row 1 becomes [0,0,0] and column 1 becomes [0,0,0].
example_2.py — 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 to become all zeros, and columns 0 and 3 to become zeros. The intersecting cells follow the zero rule.
example_3.py — Single Element Matrix
$
Input:
matrix = [[0]]
›
Output:
[[0]]
💡 Note:
Edge case: A single-element matrix containing zero remains unchanged since there are no other rows or columns to modify.
Time & Space Complexity
Time Complexity
O(m*n)
Single pass through the matrix with some additional first row/column processing
✓ Linear Growth
Space Complexity
O(1)
Only using two boolean flags and repurposing existing matrix cells as markers
✓ Linear Space
Constraints
- m == matrix.length
- n == matrix[0].length
- 1 ≤ m, n ≤ 200
- -231 ≤ matrix[i][j] ≤ 231 - 1
- Follow up: A straightforward solution using O(mn) space is probably a bad idea. A simple improvement uses O(m + n) space, but still not the best solution. Could you devise a constant space solution?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code