Skip to main content
CodeOath
← All problems

Problem

Set Matrix Zeroes

Medium
  • matrix

Wherever matrix holds a 0, the whole row and the whole column of that cell must be 0 in the result. Only the zeros that were in matrix at the start count. A zero created by this rule does not spread any further.

Return the resulting matrix.

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

the single 0 in row 1, column 1 clears its own row and its own column.

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

the zeros sit in rows 0 and 1 and in columns 1 and 2, so only the 7 in the bottom-left corner survives. The new zero in the top-left corner does not clear column 0.

Constraints:

  • matrix has at least one row, and every row has the same length

Follow-up: can you do it inside matrix itself, with a constant amount of extra memory, and return it?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.