MediumNo. 0073

Set Matrix Zeroes — LeetCode 73 Python Solution

Topics
Array, Hash Table, Matrix
Reading time
2 min

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

PythonSolution
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] = 0

Complexity

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.