InterviewPrepKit

Home / Coding / Math & Geometry

Set Matrix Zeroes

medium Original ↗
Solving tips
  • Spot the cascade trap: separate a detect pass (find all original zeros) from an apply pass, or written zeros will trigger extra clearing.
  • For O(1) space, reuse the first row and first column as marker arrays; track whether row 0 and col 0 themselves need clearing with two separate boolean flags.
  • Target O(m*n) time and O(1) extra space (the two flags are the only auxiliary storage).
  • Common pitfall: compute the first-row/first-col flags before the inner marking overwrites (0,0), and clear the first row/column LAST since the markers live there.

Problem

You are given an m x n integer matrix. If any cell contains 0, set that cell’s entire row and entire column to 0. Do it in place, mutating the given matrix.

The subtlety: the zeroing must be based on the original positions of the zeros. A zero you write during the process must not trigger further rows/columns to be cleared.

Examples

  • [[1,1,1],[1,0,1],[1,1,1]][[1,0,1],[0,0,0],[1,0,1]] — the single 0 at (1,1) clears row 1 and column 1.
  • [[0,1,2,0],[3,4,5,2],[1,3,1,5]][[0,0,0,0],[0,4,5,0],[0,3,1,0]] — zeros in row 0 clear columns 0 and 3, and row 0 itself.
  • [[1,2,3],[4,5,6]][[1,2,3],[4,5,6]] — no zeros, nothing changes.

Constraints

  • m == len(matrix), n == len(matrix[0])
  • 1 <= m, n <= 200
  • -2^31 <= matrix[i][j] <= 2^31 - 1
  • Follow-ups: an O(m·n) space solution is trivial; O(m + n) is better; the target is a constant-space solution.

Think about it first

Hint 1 The danger is cascading: if you zero a row as soon as you see a `0`, later cells in that row look like original zeros. So first *find* all the zeros, then *apply* the clearing in a second phase.
Hint 2 Remembering which rows and which columns must be cleared needs only two sets (or two boolean arrays) of size `m` and `n` — that's O(m + n) space, independent of how many zeros there are.
Hint 3 To reach O(1) space, store those row/column flags *inside the matrix itself*: use the first row and first column as marker arrays. Handle the first row and first column specially with a couple of standalone boolean flags, because they overlap at cell `(0,0)`.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.