Set Matrix Zeroes

MediumMatrixin-place markers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an m x n integer grid matrix, modify it **in place** so that whenever a cell originally holds the value 0, every other cell sharing that cell's row or column is also set to 0. The key subtlety is the word *originally*: the propagation must be based on the positions of the zeros that existed when you started. If you naively write zeros into the grid as you scan it, those freshly written zeros can be mistaken for original zeros and end up wiping out rows and columns that should have been left untouched. A straightforward approach records the rows and columns that contain a zero using two auxiliary arrays, then performs a second pass to clear them. The more interesting challenge — and the one this problem is really after — is to do the same work using only O(1) extra space by reusing the matrix's own first row and first column as bookkeeping markers. Return the same matrix after applying the transformation.

Examples

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
The single zero sits at row 1, column 1, so that entire row and column are zeroed out.
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Zeros in the first row appear at columns 0 and 3, so both of those columns plus the entire first row become zero.
Input: matrix = [[5,2,3],[4,6,7]]
Output: [[5,2,3],[4,6,7]]
There are no zeros in the grid, so nothing changes.

Constraints

  • `m == matrix.length`
  • `n == matrix[0].length`
  • `1 <= m, n <= 200`
  • `-2^31 <= matrix[i][j] <= 2^31 - 1`
  • Aim for an in-place solution that uses `O(1)` additional space.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.