#73
Set Matrix Zeroes
MediumArrayHash TableMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n) | O(m * n) |
| Space | O(m * n) | O(1) |
💡
Intuition
Time O(m * n)Space O(1)
The optimal approach uses the first row and first column of the matrix itself to mark which rows and columns need to be zeroed. This allows us to achieve the task in place without using extra space.
⚙️
Algorithm
4 steps- 1Step 1: Use the first row and first column to mark which rows and columns should be zeroed.
- 2Step 2: Iterate through the matrix (excluding the first row and column) and mark the first row and column if a zero is found.
- 3Step 3: Zero out the marked rows and columns based on the markers in the first row and column.
- 4Step 4: Finally, zero out the first row and first column if they were marked.
solution.py19 lines
1def setZeroes(matrix):
2 m, n = len(matrix), len(matrix[0])
3 row_zero = any(matrix[0][j] == 0 for j in range(n))
4 col_zero = any(matrix[i][0] == 0 for i in range(m))
5 for i in range(1, m):
6 for j in range(1, n):
7 if matrix[i][j] == 0:
8 matrix[i][0] = 0
9 matrix[0][j] = 0
10 for i in range(1, m):
11 for j in range(1, n):
12 if matrix[i][0] == 0 or matrix[0][j] == 0:
13 matrix[i][j] = 0
14 if row_zero:
15 for j in range(n):
16 matrix[0][j] = 0
17 if col_zero:
18 for i in range(m):
19 matrix[i][0] = 0ℹ
Complexity note: This complexity is due to the single pass through the matrix to mark rows and columns, and we use the matrix itself for marking, thus requiring constant space.
- 1Using the first row and column to mark zeros allows us to avoid using extra space.
- 2Always consider in-place modifications to save memory.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.