MediumNo. 0073
Set Matrix Zeroes — LeetCode 73 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Hash Table, Matrix
- On study lists
- Blind 75, NeetCode 150 and Top Interview 150
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- matrix = [[1,1,1],[1,0,1],[1,1,1]]
- Output
- [[1,0,1],[0,0,0],[1,0,1]]
Python solution
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
m, n = len(matrix), len(matrix[0])
row = [False] * m
col = [False] * n
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
row[i] = col[j] = True
for i in range(m):
for j in range(n):
if row[i] or col[j]:
matrix[i][j] = 0Complexity
- Time
- O(m × n)
- Space · auxiliary
- O(m+n)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 73. Set Matrix Zeroes is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0036 | Valid Sudoku | Medium |
| 0037 | Sudoku Solver | Hard |
| 0840 | Magic Squares In Grid | Medium |
| 0959 | Regions Cut By Slashes | Medium |
| 1072 | Flip Columns For Maximum Number of Equal Rows | Medium |
| 1074 | Number of Submatrices That Sum to Target | Hard |
Frequently asked questions
- How hard is LeetCode 73. Set Matrix Zeroes?
LeetCode 73. Set Matrix Zeroes is rated Medium on LeetCode.
- What is the time complexity of LeetCode 73. Set Matrix Zeroes?
The Python solution on this page runs in O(m × n).
- What is the space complexity of LeetCode 73. Set Matrix Zeroes?
The Python solution on this page uses O(m+n) auxiliary space.
- What topics does LeetCode 73. Set Matrix Zeroes cover?
LeetCode 73. Set Matrix Zeroes is tagged Array, Hash Table and Matrix on LeetCode.