Blind 75
70 / 75Free practice

Set Matrix Zeroes

Medium · Matrices

Jump to code

If any entry in a rectangular matrix is zero, make its entire row and column zero. Perform the update in place using constant auxiliary space.

Examples

Example 1

matrix = [[1,1,1],[1,0,1],[1,1,1]]

Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2

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]]

Constraints

  • 1 <= matrix.length, matrix[0].length <= 100
  • -2^31 <= matrix[i][j] <= (2^31) - 1

Function contract

Modify matrix in place. The grader checks its value after your function returns.

Need a hint?

The first row and column can store markers, but their original zero status must be saved.

Real matrix interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    [
      1,
      1,
      1
    ],
    [
      1,
      0,
      1
    ],
    [
      1,
      1,
      1
    ]
  ]
]
Expected
[
  [
    1,
    0,
    1
  ],
  [
    0,
    0,
    0
  ],
  [
    1,
    0,
    1
  ]
]
Case 2
Input
[
  [
    [
      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
Input
[
  [
    [
      1,
      2
    ],
    [
      3,
      4
    ]
  ]
]
Expected
[
  [
    1,
    2
  ],
  [
    3,
    4
  ]
]
Case 4
Input
[
  [
    [
      0,
      1
    ],
    [
      2,
      3
    ]
  ]
]
Expected
[
  [
    0,
    0
  ],
  [
    0,
    3
  ]
]
Case 5
Input
[
  [
    [
      1,
      0,
      3
    ],
    [
      4,
      5,
      6
    ],
    [
      0,
      8,
      9
    ]
  ]
]
Expected
[
  [
    0,
    0,
    0
  ],
  [
    0,
    0,
    6
  ],
  [
    0,
    0,
    0
  ]
]

Drafts are saved per language in this browser when storage is available.