NeetCode #906LC-73MediumMath & GeometryBlind 75NC 150NC 250
← Back to All Problems

#906 · #73 · Set Matrix Zeroes(矩阵置零)

📌 Problem Statement & Constraints

Given an m x n integer matrix, if an element is 0, set its entire row and column to 0, modifying the matrix in place. Constraints: 1 <= m, n <= 200, -2^31 <= matrix[i][j] <= 2^31 - 1. The follow-up asks for an O(1) extra-space solution.

💡 Core Algorithmic Approaches

  1. Use the first row and first column of the matrix itself as the marker arrays: a 0 written at matrix[i][0] records that row i must be zeroed, and a 0 at matrix[0][j] records that column j must be zeroed.
  2. Before those marker cells are overwritten, save two flags recording whether the first row and the first column originally contained a zero.
  3. First pass over the inner submatrix [1..m-1] x [1..n-1] writes the markers; a second pass over the same submatrix reads them and zeroes cells.
  4. Finally apply the two saved flags. Order matters: the inner submatrix is processed before the first row and column, so their markers are still intact when read.

💻 Benchmark Python3 Implementation

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        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))

        # use the first row / column as marker storage
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0
                    matrix[0][j] = 0

        # zero the inner cells using the 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

        # finally handle the first row and column themselves
        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

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(m * n): a constant number of full passes over the matrix.
💾 Space Complexity
O(1): only two boolean flags beyond the input.

⚠️ Interview Pitfalls & Follow-ups

  • Zeroing the first row/column before the inner pass: that destroys the markers, so the first row and column must be handled last.
  • Forgetting the two flags: a zero that originated in the first row would be lost once the marker cells are overwritten.
  • Writing markers into the inner cells themselves: that creates cascading false zeros.
  • Using a separate rows/cols set: correct, but it costs O(m + n) space, which the follow-up explicitly forbids.