Skip to main content

🟨 Set Matrix Zeroes (#73)

📋 Problem Statement

Given an m x n integer matrix, if an element is 0, set its entire row and column to 0's.

You must do it in place.

💡 Examples

Example 1

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

🔑 Key Insights & Approach

Core Observation: Use first row and column as markers. Process special case for first row/col separately.

Why First Row/Col as Markers?

  • O(m * n) time, O(1) space
  • In-place solution
  • Clever use of existing space

Pattern: "In-Place Matrix Marking" pattern.

🐍 Solution: Python

Approach: O(1) Space

Time Complexity: O(m * n) | Space Complexity: O(1)

from typing import List

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 first row/col as markers
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

# Set zeros 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
if first_row_zero:
for j in range(n):
matrix[0][j] = 0

# Handle first col
if first_col_zero:
for i in range(m):
matrix[i][0] = 0

🔵 Solution: Golang

Approach: O(1) Space

Time Complexity: O(m * n) | Space Complexity: O(1)

func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
firstRowZero, firstColZero := false, false

for j := 0; j < n; j++ {
if matrix[0][j] == 0 {
firstRowZero = true
break
}
}

for i := 0; i < m; i++ {
if matrix[i][0] == 0 {
firstColZero = true
break
}
}

for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if matrix[i][j] == 0 {
matrix[i][0] = 0
matrix[0][j] = 0
}
}
}

for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if matrix[i][0] == 0 || matrix[0][j] == 0 {
matrix[i][j] = 0
}
}
}

if firstRowZero {
for j := 0; j < n; j++ {
matrix[0][j] = 0
}
}

if firstColZero {
for i := 0; i < m; i++ {
matrix[i][0] = 0
}
}
}

📚 References