TRT
Sign in
mediumFoundationsLeetCode#in-place markers#space trade-off

Set matrix zeroes

Zero every row and column that contains a 0, first with O(m + n) extra memory and then with O(1).

The Runtime Theory Team1 min read
Taught inSpace and hidden costsTime is only one bill an algorithm pays. Memory is the other, and both hide in copies, allocations, recursion and constant factors that Big-O leaves out.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inmatrix = [[1,1,1],[1,0,1],[1,1,1]]

out[[1,0,1],[0,0,0],[1,0,1]]

inmatrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]

out[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

inmatrix = [[1]]

out[[1]]

Given an m × n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Before you code

Zeroing as you scan is wrong: the zeros you write look like original zeros and spread across the whole matrix. You need to record which rows and columns to clear before clearing any. The question is where to keep that record.

Hints

  1. Easy version: two boolean arrays of sizes m and n. That is O(m + n) extra space.
  2. O(1) version: use the first row and first column of the matrix itself as those two arrays.
  3. The first row and column then need their own flags, because their markers overlap at matrix[0][0]. Record whether each originally contained a 0 before using them as markers.
  4. Clear the inner cells first, and the first row and column last.

Production & complexity notes

When solving Set matrix zeroes on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Space and hidden costs to reinforce the underlying pattern.

What it practices

Measuring and reducing extra space, from Space and hidden costs.

Not started

Sign in to save your learning progress.

Sign in to save