You get an m × n grid of integers, matrix. Wherever a cell holds 0, every cell in that cell's row and every cell in its column must become 0 as well.
Change matrix in place; nothing is returned. Only the zeros that were there at the start count: a cell you zero along the way does not wipe out its own row and column.
Example 1
Input: matrix = [[5, 1, 7], [2, 0, 3], [4, 6, 8]] Output: [[5, 0, 7], [0, 0, 0], [4, 0, 8]] Why: the 0 in the middle clears row 1 and column 1
1 more example and the constraints
Example 2
Input: matrix = [[0, 4, 1], [3, 2, 6]] Output: [[0, 0, 0], [0, 2, 6]] Why: the 0 in the corner clears row 0 and column 0
Constraints
- 1 ≤ m, n ≤ 200
- −2³¹ ≤ matrix[i][j] ≤ 2³¹ − 1
- Follow-up: use O(1) extra space
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Remember rows and columnsO(m · n)
- Mark in the first row and columnO(m · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 200 × 200 grid | Verdict |
|---|---|---|---|
| Remember rows and columns | O(m · n) | Passes; O(m + n) extra space | |
| Mark in the first row and column | O(m · n) | Best; meets the O(1) follow-up |
m = rows, n = columns. Both read every cell a constant number of times.
Edge cases to test
- A 0 in the first row or column. [[0, 4, 1], [3, 2, 6]] needs the two flags; the marker cells alone cannot tell.
- One row or one column. [[1, 0, 3, 4]] becomes all zeros: the row has a 0.
- No zeros at all. Nothing changes.
- Extreme values. Any int can appear, so a sentinel like −1 to mean "clear later" is not safe.
Common mistakes
- Zeroing rows and columns during the first scan, so new zeros spread across the whole grid.
- Using matrix[0][0] for both the first row and the first column, which mixes up their flags.
- Clearing the first row or column before the inner cells have read their markers.
How to talk through it
- 1Clarify. In place, nothing returned? Do only the original zeros count? What values can appear?
- 2Explain the trap. Zeroing while scanning creates new zeros, so the zeros must be recorded first.
- 3Give the two-set version. Note zero rows and columns, then clear; O(m · n) time and O(m + n) space.
- 4Move the flags into the grid. Use the first row and column as markers, with two booleans for themselves.
- 5Test out loud. Run a 0 in the corner, a single row, and a grid without zeros.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?