CodeArchon

mediumMath & GeometryFacebookMicrosoft

Zero-Wave Flooder

A quality inspector zeroes out every row and column that contains a defective cell, using constant extra space.

Given an m×n matrix, if an element is 0, set its entire row and column to 0. Do it in place with O(1) extra space (other than two flags).

Choose approach

1
1
1
1
0
1
1
1
1
1/3
Narrationstep 1 of 3

firstRow=false, firstCol=false. Mark headers.

1def setZeroes(matrix):
2 m, n = len(matrix), len(matrix[0])
3 firstRow = any(matrix[0][j] == 0 for j in range(n))
4 firstCol = any(matrix[i][0] == 0 for i in range(m))
5 for i in range(1, m):
6 for j in range(1, n):
7 if matrix[i][j] == 0:
8 matrix[i][0] = matrix[0][j] = 0
9 for i in range(1, m):
10 for j in range(1, n):
11 if matrix[i][0] == 0 or matrix[0][j] == 0:
12 matrix[i][j] = 0
13 if firstRow:
14 for j in range(n): matrix[0][j] = 0
15 if firstCol:
16 for i in range(m): matrix[i][0] = 0
Variables
firstRow=false
firstCol=false

How to think about it

  1. Markers reuse existing storage.
  2. First row/col must be preserved via flags until last.

Edge cases to catch in interview

  • No zeros -> unchanged.
  • All zeros -> all zeros.

Examples

Example 1[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
{"grid":[[0,1,2,0],[3,4,5,2],[1,3,1,5]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed