Set Matrix Zeroes

Medium#73marks on the edges

You get a matrix of numbers. Wherever there is a 0, make its whole row and its whole column 0. Change the matrix in place, and the rows and columns to clear are the ones that had a zero at the start, not ones that got zeros along the way. Our example: [5, 2, 7, 1], [3, 0, 4, 6], [0, 8, 9, 2], [7, 1, 3, 5] → [0, 0, 7, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 3, 5].

input
matrix: an m × n grid of integers.
returns
Nothing: change matrix in place so that every row and every column that held a 0 is all zeros. Only the zeros that were there at the start count.
constraints
  • 1 ≤ m, n ≤ 100, matrix[i].length = n
  • −2³¹ ≤ matrix[i][j] ≤ 2³¹ − 1
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
function setZeroes(matrix) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more matrix traversal problems

Pattern “Matrix traversal” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.