Problem: Set Matrix Zeroes
If a cell is zero, set its entire row and column to zero in place.
Hidden answer: strategy, invariant, mistakes, tests
Use the first row and first column as marker storage, plus flags for
whether they originally contained zero. Invariant: after the marker
pass, matrix[r][0] and matrix[0][c]
encode whether row r or column c should be
zeroed. Mistake to avoid: overwriting markers before the inner cells
are processed. Test one row, one column, zero at [0][0],
and multiple zeroes.
Problem: Spiral Matrix
Return all matrix values in spiral order.
Hidden answer: strategy, invariant, mistakes, tests
Maintain top, bottom, left, and right boundaries. Invariant: after
each side traversal, the corresponding boundary moves inward and no
visited cell remains inside the active rectangle. Mistake to avoid:
traversing bottom or left after the boundaries have crossed. Test
square, single row, single column, wide rectangle, and tall
rectangle.
Problem: Rotate Image
Rotate an n x n matrix 90 degrees clockwise in place.
Hidden answer: strategy, invariant, mistakes, tests
Transpose across the main diagonal, then reverse each row. Invariant
after transpose: matrix[r][c] has swapped with
matrix[c][r] exactly once for c > r.
Mistake to avoid: swapping each pair twice. Test 1 x 1,
2 x 2, odd size, and even size.
Worked Python: Spiral Matrix
Implement the boundary walk without duplicate visits.
Hidden answer: Python solution
def spiral_order(matrix):
if not matrix or not matrix[0]:
return []
out = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
out.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
out.append(matrix[r][left])
left += 1
return out