← Math & Geometry

Drill #119 — Set Matrix Zeroes

Medium In-place Markers Math & Geometry

In plain English: If any cell in a grid is zero, zero out its entire row and column.

Use the first row and first column as markers. First pass: mark which rows/cols need zeroing. Second pass: zero based on markers. Handle the first row/col separately with a flag.

Prompt

Given an m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Try to write it from scratch before scrolling down.

Solution

def set_zeroes(matrix):
    m, n = len(matrix), len(matrix[0])
    first_row_zero = any(matrix[0][j] == 0 for j in range(n))
    first_col_zero = any(matrix[i][0] == 0 for i in range(m))

    # mark zeros in first row/col
    for i in range(1, m):
        for j in range(1, n):
            if matrix[i][j] == 0:
                matrix[i][0] = 0  # mark row
                matrix[0][j] = 0  # mark col

    # zero cells based on markers
    for i in range(1, m):
        for j in range(1, n):
            if matrix[i][0] == 0 or matrix[0][j] == 0:
                matrix[i][j] = 0

    # handle first row and col
    if first_row_zero:
        for j in range(n):
            matrix[0][j] = 0
    if first_col_zero:
        for i in range(m):
            matrix[i][0] = 0
    return matrix

# Test: set_zeroes([[1,1,1],[1,0,1],[1,1,1]])
#       == [[1,0,1],[0,0,0],[1,0,1]]
O(m*n) time · O(1) space

Related Micro Drills

← Drill #118