Set Matrix Zeroes
Master this topic with zero to advance depth.
Set Matrix Zeroes
If an element is 0, we must mark its row and column. To do this in-place, we can use the first row and first column of the matrix itself as auxiliary storage (flags).
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.
Visual Representation
Matrix:
[1, 1, 1]
[1, 0, 1]
[1, 1, 1]
Output:
[1, 0, 1]
[0, 0, 0]
[1, 0, 1]Examples
The element at (1,1) is 0, so row 1 and column 1 are set to 0.
Elements at (0,0) and (0,3) are 0, so their rows and columns are set to 0.
Level I: Brute Force (Extra Matrix)
Intuition
Create a copy of the matrix. If an element in the original is 0, set the entire row and column in the copy to 0. This is simple but uses O(M*N) extra space and involves redundant work.
Detailed Dry Run
Matrix Copy Trace
matrix = [[1, 0], [1, 1]]
copy = [[1, 0], [1, 1]]- Find 0 at (0, 1)
- In
copy: Set row 0 to 0s, col 1 to 0s. copybecomes[[0, 0], [1, 0]]- Update original
matrixwithcopyvalues.
Level II: Row and Column Auxiliary Arrays
Intuition
We can improve the space complexity by using two auxiliary boolean arrays: row of size m and col of size n. If matrix[i][j] == 0, we set row[i] = true and col[j] = true. Finally, we traverse the matrix again and set matrix[i][j] = 0 if row[i] or col[j] is true.
Detailed Dry Run
| Row Flags | Col Flags | i, j | Action |
|---|---|---|---|
| [F, T, F] | [F, T, F] | 1, 1 | matrix[1][1]=0, so row[1]=T, col[1]=T |
| [F, T, F] | [F, T, F] | 0, 1 | row[0]=F, col[1]=T -> matrix[0][1]=0 |
Level III: Optimal Solution (In-place Flags)
Intuition
Use the first row and first column of the matrix itself to store flags for which rows and columns should be zeroed.
- Use two variables
row0andcol0to track if the first row and column themselves need to be zeroed. - Iterate through the rest of the matrix, and if
matrix[i][j] == 0, setmatrix[i][0] = 0andmatrix[0][j] = 0. - Finally, zero out cells based on flags, then the first row/column.
Detailed Dry Run
Visual Process
matrix = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
Initial Scan:
Found 0 at (1, 1) -> Mark First Row/Col
[1, 0, 1] (matrix[0][1] = 0)
[0, 0, 1] (matrix[1][0] = 0)
[1, 1, 1]
Final Update (excluding row0/col0):
[1, 0, 1]
[0, 0, 0] (Row 1 was marked)
[1, 0, 1] (Col 1 was marked)Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.