Set Matrix Zeroes

35 min · setZeroes()

One zero in a spreadsheet can wipe out a whole cross of cells.

You're given an m x n integer matrix. For every cell that is 0 in the original matrix, set its entire row and its entire column to 0. Return the finished matrix.

Only the original zero positions decide which rows and columns are cleared. A zero you write during the transformation doesn't create another wave of changes.

You may update the input matrix itself. Either way, return the matrix after all required rows and columns have been cleared.

Constraints

  • 1 <= m, n <= 100
  • matrix has exactly m rows, and every row has exactly n values.
  • -1_000 <= matrix[i][j] <= 1_000

Hints

Remember before you write

First scan the untouched matrix and record every row and column containing a zero. Only then should you change values.

The matrix can hold its own notes

Instead of external sets, use matrix[row][0] to mark a row and matrix[0][col] to mark a column. Apply those markers only after the marking pass ends.

One cell has two jobs

matrix[0][0] belongs to both the first row and first column, so it can't remember both states. Save two booleans for whether the original first row and first column contained a zero.

Follow-up

Can you perform the transformation with O(1) extra working space?

Visible cases

Examples

Example 1

ready
Input
matrix = [
  [
    1,
    1,
    1
  ],
  [
    1,
    0,
    1
  ],
  [
    1,
    1,
    1
  ]
]
Expected
[
  [
    1,
    0,
    1
  ],
  [
    0,
    0,
    0
  ],
  [
    1,
    0,
    1
  ]
]
Why
the center zero clears its middle row and middle column

Example 2

ready
Input
matrix = [
  [
    0,
    1,
    2,
    0
  ],
  [
    3,
    4,
    5,
    2
  ],
  [
    1,
    3,
    1,
    5
  ]
]
Expected
[
  [
    0,
    0,
    0,
    0
  ],
  [
    0,
    4,
    5,
    0
  ],
  [
    0,
    3,
    1,
    0
  ]
]
Why
two zeros in the first row clear that row plus the first and last columns

Example 3

ready
Input
matrix = [
  [
    1,
    2
  ],
  [
    3,
    0
  ]
]
Expected
[
  [
    1,
    0
  ],
  [
    0,
    0
  ]
]
Why
a corner zero clears its row and column without spreading again

Interview signal

Asked at

AmazonMicrosoftMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite