Core Insight Name the mathematical relationship first, then apply it consistently to every position or digit.
Common Pitfall Write down index and boundary conditions before mutating an in-place structure.
Description
Set rows and columns to zero when a zero is found.
Constraints
- Time Complexity:
O(m·n) - Space Complexity:
O(1)
Tags
arrayhash-tablematrix
Implementation Plan Translate the invariant into these small, testable moves.
- Identify the formula or transformation.
- Set boundary conditions.
- Process each required position.
- Return the transformed result.
def setZeroes(matrix):
ROWS, COLS = len(matrix), len(matrix[0])
rowZero = False
for r in range(ROWS):
for c in range(COLS):
if matrix[r][c] == 0:
matrix[0][c] = 0
if r > 0:
matrix[r][0] = 0
else:
rowZero = True
for r in range(1, ROWS):
for c in range(1, COLS):
if matrix[0][c] == 0 or matrix[r][0] == 0:
matrix[r][c] = 0
if matrix[0][0] == 0:
for r in range(ROWS):
matrix[r][0] = 0
if rowZero:
for c in range(COLS):
matrix[0][c] = 0