Set Matrix Zeroes (LeetCode 73): Solution and Explanation

Medium
Array
Hash Table
Matrix

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Scan every cell. When matrix[r][c] is 0, set matrix[0][c] = 0 to mark its column.
  2. For the row marker, set matrix[r][0] = 0 when r > 0. If r is 0, set rowZero = True instead, because row 0 has no separate marker cell.
  3. For every interior cell with r >= 1 and c >= 1, set it to 0 if its column marker matrix[0][c] or its row marker matrix[r][0] is 0.
  4. If matrix[0][0] is 0, column 0 must be cleared, so zero every matrix[r][0].
  5. If rowZero is 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]]
  1. 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 rowZero to True because they are in row 0.
  2. No other cell is 0, so the row markers matrix[1][0] and matrix[2][0] stay nonzero.
  3. In the interior pass, only column 3 has a zero marker, so matrix[1][3] and matrix[2][3] become 0.
  4. matrix[0][0] is 0, so column 0 is cleared: matrix[1][0] and matrix[2][0] become 0.
  5. rowZero is 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] = 0

Time and space complexity

Time

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).

Space

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.