Practice · Math and matrices · 3 of 3

Zero Out Rows and Columns

You are given matrix, a grid of integers with m rows and n columns. For every cell that holds 0, set every value in its row and every value in its column to 0.

Only the zeros that are there at the start count: a zero you write must not clear any more rows or columns. Change matrix in place; there is nothing to return.

Using O(m + n) extra memory is fine. Using only a constant amount is a stretch goal.

Example 1

Input
matrix = [[5, 2, 7], [3, 0, 8], [6, 4, 9]]
Output
[[5, 0, 7], [0, 0, 0], [6, 0, 9]]
The 0 in the middle clears row 1 and column 1.

Example 2

Input
matrix = [[0, 4, 2, 0], [3, 5, 1, 6], [7, 8, -1, 9]]
Output
[[0, 0, 0, 0], [0, 5, 1, 0], [0, 8, -1, 0]]
The two zeros in row 0 clear that row, and columns 0 and 3.

Constraints

  • 1 ≤ m, n ≤ 200
  • −2³¹ ≤ matrix[r][c] ≤ 2³¹ − 1, so any value, negative ones included, can sit next to a zero.