0
0
DSA Pythonprogramming

Set Matrix Zeroes In Place in DSA Python

Choose your learning style9 modes available
Mental Model
When a cell in a matrix is zero, set its entire row and column to zero without using extra space.
Analogy: Imagine a grid of lights where if one light goes off, the entire row and column of lights must also go off, but you only have one chance to mark which rows and columns to turn off without extra sticky notes.
Matrix before:
1 1 1
1 0 1
1 1 1

We want to mark rows and columns to zero without extra space.
Dry Run Walkthrough
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Goal: Set entire row and column to zero for every cell that is zero, modifying matrix in place.
Step 1: Check first row and first column for zeros to remember if they need zeroing later
First row: 1 1 1
First column: 1 1 1
Why: We need to know if first row or column should be zeroed later since we will use them as markers
Step 2: Traverse matrix from row 1 and col 1, mark zeros in first row and column
Matrix after marking:
1 0 1
0 0 1
1 1 1
Why: Mark rows and columns to zero by setting first cell of that row and column to zero
Step 3: Zero rows based on marks in first column
Matrix after zeroing rows:
1 0 1
0 0 0
1 1 1
Why: Rows with zero in first column must be zeroed
Step 4: Zero columns based on marks in first row
Matrix after zeroing columns:
1 0 1
0 0 0
1 0 1
Why: Columns with zero in first row must be zeroed
Step 5: Zero first row and first column if needed (none in this example)
Final matrix:
1 0 1
0 0 0
1 0 1
Why: Apply zeroing to first row and column if they originally had zeros
Result:
1 0 1
0 0 0
1 0 1
Annotated Code
DSA Python
from typing import List

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        rows, cols = len(matrix), len(matrix[0])
        first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
        first_col_zero = any(matrix[i][0] == 0 for i in range(rows))

        # Mark zeros on first row and column
        for i in range(1, rows):
            for j in range(1, cols):
                if matrix[i][j] == 0:
                    matrix[i][0] = 0  # mark row
                    matrix[0][j] = 0  # mark column

        # Zero rows based on marks
        for i in range(1, rows):
            if matrix[i][0] == 0:
                for j in range(cols):
                    matrix[i][j] = 0

        # Zero columns based on marks
        for j in range(1, cols):
            if matrix[0][j] == 0:
                for i in range(rows):
                    matrix[i][j] = 0

        # Zero first row if needed
        if first_row_zero:
            for j in range(cols):
                matrix[0][j] = 0

        # Zero first column if needed
        if first_col_zero:
            for i in range(rows):
                matrix[i][0] = 0


# Driver code
matrix = [
    [1,1,1],
    [1,0,1],
    [1,1,1]
]

sol = Solution()
sol.setZeroes(matrix)
for row in matrix:
    print(' '.join(str(x) for x in row))
first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
Check if first row has any zero to handle separately later
first_col_zero = any(matrix[i][0] == 0 for i in range(rows))
Check if first column has any zero to handle separately later
for i in range(1, rows): for j in range(1, cols): if matrix[i][j] == 0: matrix[i][0] = 0 matrix[0][j] = 0
Mark rows and columns to be zeroed by setting first cell in row and column to zero
for i in range(1, rows): if matrix[i][0] == 0: for j in range(cols): matrix[i][j] = 0
Zero entire row if marked
for j in range(1, cols): if matrix[0][j] == 0: for i in range(rows): matrix[i][j] = 0
Zero entire column if marked
if first_row_zero: for j in range(cols): matrix[0][j] = 0
Zero first row if originally had zero
if first_col_zero: for i in range(rows): matrix[i][0] = 0
Zero first column if originally had zero
OutputSuccess
1 0 1 0 0 0 1 0 1
Complexity Analysis
Time: O(m*n) because we scan the entire matrix multiple times but each cell is visited a constant number of times
Space: O(1) because we use the matrix itself for marking without extra space
vs Alternative: Naive approach uses extra O(m+n) space for row and column markers, this approach saves space by using first row and column as markers
Edge Cases
Matrix with no zeros
Matrix remains unchanged
DSA Python
first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
Matrix with zero in first row and first column
First row and column are zeroed correctly after marking
DSA Python
if first_row_zero:
    for j in range(cols):
        matrix[0][j] = 0
Matrix with single element zero
Single element matrix zeroed correctly
DSA Python
first_row_zero = any(matrix[0][j] == 0 for j in range(cols))
When to Use This Pattern
When you need to set entire rows and columns to zero based on zero cells without extra space, use the first row and column as markers to track zeroing.
Common Mistakes
Mistake: Using extra arrays for marking rows and columns, increasing space complexity
Fix: Use the first row and first column of the matrix itself as markers to save space
Mistake: Zeroing first row and column too early, losing marker information
Fix: Check and store if first row and column need zeroing before marking, then zero them last
Summary
Sets entire rows and columns to zero in a matrix if any cell in them is zero, modifying the matrix in place.
Use when you want to save space and avoid extra memory while zeroing rows and columns based on zero cells.
The key insight is to use the first row and first column as markers to track which rows and columns to zero.