InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Set Matrix Zeroes

medium Original ↗ 00:00

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 zeroing must be based on the original positions of the zeros. A zero written during the process must not trigger additional rows or 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 If you zero a row as soon as you see a `0`, later cells in that row look like original zeros and the clearing cascades. 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)`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug