Skip to content
mlmentorship

Set Matrix Zeroes

If a cell is zero, set its full row and column to zero. Change the matrix in place.

Published · 12 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Set Matrix Zeroes

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A rectangular integer matrix whose rows are distinct mutable lists. Output. Modify the matrix in place and return None. Every row or column containing a zero in the original matrix must become all zeros. Rules. Newly written zeros must not trigger further propagation beyond those original rows and columns. Other cells retain their original values. Negative and repeated nonzero values are allowed. Empty dimensions do nothing. The reference may replace the first row object as well as changing cells. Example. [[1, 1, 1], [1, 0, 1], [1, 1, 1]] becomes [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. The four corner cells stay 1 because their original rows and columns contained no zero.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Preserve first-row and first-column facts, store interior zero instructions in those borders, then apply markers before restoring the borders.

Problem trace

Marker zeros record instructions, not new original zero locations

Input and goalIf a cell is zero, set its full row and column to zero. Change the matrix in place.
Inspect the original bordersThe first row contains zero. The first column does not.
10scan3456780
coordinatesrow,columnfirstRowZerotruefirstColZerofalseactionsave border facts before overwriting markers
scan
(0, 1)
coordinates
row,column
first row zero
true

Recognize it
Use border markers when entire rows and columns must change from discovered cells, but the required extra space must remain constant.
Keep true
After the marker pass, matrix[r][0]=0 means interior row r must be zeroed and matrix[0][c]=0 means interior column c must be zeroed; saved booleans independently preserve the original first-border obligations.
Reuse it
When output overwrites input, identify safe in-place metadata cells and separately save any original facts those cells represented before reusing them.
The first row contains zero. The first column does not. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does a marker zero not imply that the original first column was entirely zero?
Full interview answer 12 min read
Reading depth

Update a matrix so every row and column containing an original zero becomes entirely zero.

Problem

Input. A rectangular integer matrix whose rows are distinct mutable lists.

Output. Modify the matrix in place and return None. Every row or column containing a zero in the original matrix must become all zeros.

Rules. Newly written zeros must not trigger further propagation beyond those original rows and columns. Other cells retain their original values. Negative and repeated nonzero values are allowed. Empty dimensions do nothing. The reference may replace the first row object as well as changing cells.

Example. [[1, 1, 1], [1, 0, 1], [1, 1, 1]] becomes [[1, 0, 1], [0, 0, 0], [1, 0, 1]]. The four corner cells stay 1 because their original rows and columns contained no zero.

Picture

In [[1,0,3], [4,5,6], [7,8,0]], original zeros require rows 0,2 and columns 1,2. Save whether the first row and column originally contained zeros. Then mark interior discoveries at matrix[row][0] and matrix[0][col].

Problem trace

Separate two-row matrix: new zeros cannot create new original obligations

Worked example: new zeros must not create new row or column obligationsThe only original zero is at row 0, column 1. Final row 1 stays (1,0,1), not all zeros.Freeze original zero obligations; newzeros cannot add new onesThe only original zero is row zero,column one101111Apply only frozen row zero and columnone000101The two lower corner ones remain.Newly written top-row zeros cannotinvent extra column obligations.
Read it this way: The only original zero is at row 0, column 1. Final row 1 stays (1,0,1), not all zeros. What incorrect extra columns would be added by rescanning the newly zeroed top row?
Reference drawing

Problem trace

Marker zeros record instructions, not new original zero locations

Worked example: new zeros must not create new row or column obligationsThe only original zero is at row 0, column 1. Final row 1 stays (1,0,1), not all zeros.Freeze original zero obligations; newzeros cannot add new onesThe only original zero is row zero,column one101111Apply only frozen row zero and columnone000101The two lower corner ones remain.Newly written top-row zeros cannotinvent extra column obligations.
Execution trace
Input and goalIf a cell is zero, set its full row and column to zero. Change the matrix in place.
Inspect the original bordersThe first row contains zero. The first column does not.
10scan3456780
coordinatesrow,columnfirstRowZerotruefirstColZerofalseactionsave border facts before overwriting markers
scan
(0, 1)
coordinates
row,column
first row zero
true

Recognize it
Use border markers when entire rows and columns must change from discovered cells, but the required extra space must remain constant.
Keep true
After the marker pass, matrix[r][0]=0 means interior row r must be zeroed and matrix[0][c]=0 means interior column c must be zeroed; saved booleans independently preserve the original first-border obligations.
Reuse it
When output overwrites input, identify safe in-place metadata cells and separately save any original facts those cells represented before reusing them.
The first row contains zero. The first column does not. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does a marker zero not imply that the original first column was entirely zero?
Read it this way: The only original zero is at row 0, column 1. Final row 1 stays (1,0,1), not all zeros. What incorrect extra columns would be added by rescanning the newly zeroed top row?

Complete discovery before filling the interior, so newly written zeros never become new discoveries. Finally restore the border obligations saved before marking. The result is [[0,0,0], [4,0,0], [0,0,0]].

Code

def _mark_zero_rows_and_cols(matrix: list[list[int]]) -> None:
   for row in range(1, len(matrix)):
      for col in range(1, len(matrix[0])):
         if matrix[row][col] == 0:
            matrix[row][0] = matrix[0][col] = 0


def _fill_marked_zeroes(matrix: list[list[int]]) -> None:
   for row in range(1, len(matrix)):
      for col in range(1, len(matrix[0])):
         if matrix[row][0] == 0 or matrix[0][col] == 0:
            matrix[row][col] = 0


def set_zeroes(matrix: list[list[int]]) -> None:
   if not matrix or not matrix[0]:
      return

   first_row_zero = 0 in matrix[0]
   first_col_zero = any(row[0] == 0 for row in matrix)
   _mark_zero_rows_and_cols(matrix)
   _fill_marked_zeroes(matrix)

   if first_row_zero:
      matrix[0] = [0] * len(matrix[0])
   if first_col_zero:
      for row in matrix:
         row[0] = 0

Cost: cell operations and worst-case temporary storage for first-row replacement. Marker state itself is constant-sized.

Change the Requirement

Preserve Every Row Object

New task: Keep row identities and use constant workspace.

Picture and change: Write border zeros cellwise instead of allocating a replacement row.

Code: Reuse the two complete helpers above.

def set_zeroes_preserving_rows(matrix: list[list[int]]) -> None:
   if not matrix or not matrix[0]:
      return
   first_row_zero = 0 in matrix[0]
   first_col_zero = any(row[0] == 0 for row in matrix)
   _mark_zero_rows_and_cols(matrix)
   _fill_marked_zeroes(matrix)
   if first_row_zero:
      for col in range(len(matrix[0])):
         matrix[0][col] = 0
   if first_col_zero:
      for row in matrix:
         row[0] = 0

Check: [[1,0], [3,4]] becomes [[0,0], [3,0]], with both original row objects retained.

Use when: External row references must observe the full mutation. Time remains linear in cells; workspace becomes constant.

Leave the Input Unchanged

New task: Return an independent result.

Picture and change: Copy each row before borrowing its border cells.

Code: Call the complete row-preserving implementation above.

def zeroed_copy(matrix: list[list[int]]) -> list[list[int]]:
   result = [row[:] for row in matrix]
   set_zeroes_preserving_rows(result)
   return result

Check: zeroed_copy([[1,0], [3,4]]) returns [[0,0], [3,0]] without changing the source.

Use when: Callers retain an immutable input snapshot. Output storage is .

Reconstruct

Why not zero a row immediately upon discovery?

Reasoned answer

For [[1,0], [1,1]], immediate filling creates a new zero at (0,0). Treating that write as original evidence incorrectly clears column zero too. Separate discovery from application, and preserve original border facts before using borders as instructions.