Set Matrix Zeroes

MediumMatrix

You get an m × n matrix of integers. Wherever a cell holds 0, set every cell in its row and every cell in its column to 0.

Change matrix itself; the function returns nothing. The tests read matrix after your function returns. Only the zeros that were there at the start spread: a cell you have just set to 0 does not clear its own row and column.

Examples

Example 1
Input:  matrix = [[4, 0, 2], [7, 5, 3], [1, 8, 6]]
Output: [[0, 0, 0], [7, 0, 3], [1, 0, 6]]

The 0 sits in row 0 and column 1, so both are cleared.

Example 2
Input:  matrix = [[1, 2, 3, 4], [0, 5, 6, 7], [8, 9, 1, 0]]
Output: [[0, 2, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Two zeros clear rows 1 and 2 and columns 0 and 3. Only 2 and 3 in the top row survive.

Constraints

  • 1 ≤ m, n ≤ 200
  • -2³¹ ≤ matrix[i][j] ≤ 2³¹ - 1

Stuck?

Hint 1

If you clear rows and columns while you are still scanning, the new zeros look like original ones and spread too. Find every zero first, then clear.

Hint 2

Remember which rows and which columns hold a zero (two Sets work), then make a second pass. For O(1) space, keep those marks in the first row and first column, with one extra flag for the first column itself.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur