Facebook PixelSet Matrix Zeroes — Coding Practice
Set Matrix ZeroesMedium

Set Matrix Zeroes

Medium 13.1k55% acceptance
ArrayMatrixHash Table

Given an m × n integer matrix, if any element is 0, set its entire row and column to 0.

Do it in place — modify matrix directly — and return it.

A cell is zeroed because of an original 0; zeros you write must not trigger further rows/columns to be cleared.

Example 1
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
The single 0 clears its row (the middle row) and its column (the middle column).
Example 2
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]]
Example 3
Input: matrix = [[1,2],[3,4]]
Output: [[1,2],[3,4]]
No zeros, so nothing changes.
Constraints
  • m == matrix.length
  • n == matrix[0].length
  • 1 ≤ m, n ≤ 200
  • -2³¹ ≤ matrix[i][j] ≤ 2³¹ − 1
Asked atAmazonMicrosoftMetaOracle
JavaScript
Loading editor…
Case 1
[[1,1,1],[1,0,1],[1,1,1]]
expected: [[1,0,1],[0,0,0],[1,0,1]]
Case 2
[[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]]
Case 3
[[1,2],[3,4]]
expected: [[1,2],[3,4]]
Case 4
[[0]]
expected: [[0]]
Case 5
[[1,0,3]]
expected: [[0,0,0]]
Case 6
[[5],[0],[7]]
expected: [[0],[0],[0]]