Set Matrix Zeroes (LeetCode 73): Solution and Explanation
Given an m by n integer matrix, whenever a cell holds 0, set every value in its row and its column to 0. The change must be made in place, and the follow-up asks you to do it with constant extra memory.
Watch it run step by step
Try your own input and write the code →Intuition
The naive mistake is to zero out rows and columns as soon as you see a 0. The newly written zeros then look like original zeros, and they trigger more zeroing until most of the matrix is wiped. You need to separate the reading phase from the writing phase: first record which rows and columns must be cleared, then clear them.
The simple way to record that is two boolean arrays, one of size m for rows and one of size n for columns. That is O(m + n) space and already a fine answer. The follow-up asks for O(1), which means the markers have to live somewhere that already exists: inside the matrix itself.
The first row and first column are natural places for them. Write matrix[0][c] = 0 to mark column c and matrix[r][0] = 0 to mark row r. The catch is that the first row and first column are themselves subject to the rule, and the corner cell matrix[0][0] sits in both. The reference code lets matrix[0][0] mean column 0 and keeps one extra boolean, rowZero, for row 0. It fills in the interior first using the markers, and only then clears column 0 and row 0, so the markers are not destroyed before they are read.
Approach: First row and column as markers
- Scan every cell. When
matrix[r][c]is 0, setmatrix[0][c] = 0to mark its column. - For the row marker, set
matrix[r][0] = 0whenr > 0. Ifris 0, setrowZero = Trueinstead, because row 0 has no separate marker cell. - For every interior cell with
r >= 1andc >= 1, set it to 0 if its column markermatrix[0][c]or its row markermatrix[r][0]is 0. - If
matrix[0][0]is 0, column 0 must be cleared, so zero everymatrix[r][0]. - If
rowZerois True, zero every cell in row 0. Doing these two edges last keeps the markers intact while the interior is processed.
Step-by-step example
matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
- The first scan finds zeros at (0,0) and (0,3). Both mark their columns in row 0, which already holds 0 there, and both set
rowZeroto True because they are in row 0. - No other cell is 0, so the row markers
matrix[1][0]andmatrix[2][0]stay nonzero. - In the interior pass, only column 3 has a zero marker, so
matrix[1][3]andmatrix[2][3]become 0. matrix[0][0]is 0, so column 0 is cleared:matrix[1][0]andmatrix[2][0]become 0.rowZerois True, so row 0 is cleared. The result is [[0,0,0,0],[0,4,5,0],[0,3,1,0]].
Code: Python, Java, C++
1class Solution:
2 def setZeroes(self, matrix: List[List[int]]) -> None:
3 ROWS, COLS = len(matrix), len(matrix[0])
4 rowZero = False
5
6 for r in range(ROWS):
7 for c in range(COLS):
8 if matrix[r][c] == 0:
9 matrix[0][c] = 0
10 if r > 0:
11 matrix[r][0] = 0
12 else:
13 rowZero = True
14
15 for r in range(1, ROWS):
16 for c in range(1, COLS):
17 if matrix[0][c] == 0 or matrix[r][0] == 0:
18 matrix[r][c] = 0
19
20 if matrix[0][0] == 0:
21 for r in range(ROWS):
22 matrix[r][0] = 0
23
24 if rowZero:
25 for c in range(COLS):
26 matrix[0][c] = 01class Solution {
2 public void setZeroes(int[][] matrix) {
3 int ROWS = matrix.length, COLS = matrix[0].length;
4 boolean rowZero = false;
5
6 for (int r = 0; r < ROWS; r++) {
7 for (int c = 0; c < COLS; c++) {
8 if (matrix[r][c] == 0) {
9 matrix[0][c] = 0;
10 if (r > 0) matrix[r][0] = 0;
11 else rowZero = true;
12 }
13 }
14 }
15
16 for (int r = 1; r < ROWS; r++) {
17 for (int c = 1; c < COLS; c++) {
18 if (matrix[0][c] == 0 || matrix[r][0] == 0) {
19 matrix[r][c] = 0;
20 }
21 }
22 }
23
24 if (matrix[0][0] == 0) {
25 for (int r = 0; r < ROWS; r++) matrix[r][0] = 0;
26 }
27
28 if (rowZero) {
29 for (int c = 0; c < COLS; c++) matrix[0][c] = 0;
30 }
31 }
32}1class Solution {
2public:
3 void setZeroes(vector<vector<int>>& matrix) {
4 int ROWS = matrix.size(), COLS = matrix[0].size();
5 bool rowZero = false;
6
7 for (int r = 0; r < ROWS; r++) {
8 for (int c = 0; c < COLS; c++) {
9 if (matrix[r][c] == 0) {
10 matrix[0][c] = 0;
11 if (r > 0) matrix[r][0] = 0;
12 else rowZero = true;
13 }
14 }
15 }
16
17 for (int r = 1; r < ROWS; r++) {
18 for (int c = 1; c < COLS; c++) {
19 if (matrix[0][c] == 0 || matrix[r][0] == 0) {
20 matrix[r][c] = 0;
21 }
22 }
23 }
24
25 if (matrix[0][0] == 0) {
26 for (int r = 0; r < ROWS; r++) matrix[r][0] = 0;
27 }
28
29 if (rowZero) {
30 for (int c = 0; c < COLS; c++) matrix[0][c] = 0;
31 }
32 }
33};Time and space complexity
O(m × n)
The marking pass and the filling pass each visit every cell once, and clearing the first row and column adds O(m + n).
O(1)
The markers are stored inside the matrix, so the only extra memory is the single rowZero flag.
Other approaches
Separate row and column sets (time O(m × n), space O(m + n))
Record the indices of rows and columns that contain a zero in two sets or boolean arrays, then do a second pass that zeros any cell whose row or column is marked. It is the clearest version and the usual first answer.
Copy the matrix (time O(m × n), space O(m × n))
Read zeros from a full copy while writing to the original. It avoids the cascade problem but uses memory proportional to the whole matrix.
Common mistakes
- Zeroing rows and columns immediately during the scan, which lets newly written zeros spread to the whole matrix.
- Clearing the first row or column before the interior pass, which wipes the markers and zeros cells that should survive.
- Using
matrix[0][0]for both row 0 and column 0. It can only represent one of them, so a separate flag is required. - Starting the interior pass at index 0 instead of 1, which overwrites marker cells while they are still being read.
Frequently asked questions
How do you solve Set Matrix Zeroes with constant space?
Use the first row and first column as marker storage for which columns and rows to clear, plus one extra flag for the overlapping corner. Fill the interior from the markers, then handle the first column and first row last.
Why can't you set zeros as soon as you find them?
The zeros you write would be indistinguishable from original zeros in later cells. They would trigger further rows and columns to be cleared, which gives the wrong result.
Why does the first row need a separate flag?
The cell matrix[0][0] is both the marker for row 0 and the marker for column 0. Since one cell cannot hold two independent facts, the code uses it for column 0 and keeps rowZero for row 0.