Skip to problem
←

Set Matrix Zeroes

Medium 0 attempts

Given an m × n integer matrix, set every cell in a row or column containing an original zero to 0. Modify the given matrix in place.

Zeros introduced by your changes must not trigger further changes. For example, [[0,1],[2,3]] becomes [[0,0],[0,3]]; the bottom-right cell stays 3.

Follow-up: Can you use O(1) extra space? Storing the affected rows and columns in sets uses O(m + n) extra space.

Function contract

Implement setZeroes(matrix).

Output: Modify argument 1 in place. The editor compares its final value; the function return value is ignored.

Example 1

Input
matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output
[[1,0,1],[0,0,0],[1,0,1]]

Example 2

Input
matrix = [[0,1],[2,3]]
Output
[[0,0],[0,3]]
Constraints
  • 1 <= m, n <= 200
  • -2^31 <= matrix[i][j] <= 2^31 - 1
Topics

Use the first row and first column as markers. Scan the matrix — when a zero is found, mark the corresponding first-row and first-column cell as zero. Then do a second pass to zero out marked rows and columns. Handle the first row and column separately using two dedicated flags to avoid overwriting markers prematurely.

javascript
function setZeroes(matrix) {
  const m = matrix.length;
  const n = matrix[0].length;
  let firstRowZero = false;
  let firstColZero = false;

  for (let i = 0; i < m; i++) {
    if (matrix[i][0] === 0) firstColZero = true;
  }
  for (let j = 0; j < n; j++) {
    if (matrix[0][j] === 0) firstRowZero = true;
  }

  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][j] === 0) {
        matrix[i][0] = 0;
        matrix[0][j] = 0;
      }
    }
  }

  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][0] === 0 || matrix[0][j] === 0) {
        matrix[i][j] = 0;
      }
    }
  }

  if (firstRowZero) {
    for (let j = 0; j < n; j++) matrix[0][j] = 0;
  }
  if (firstColZero) {
    for (let i = 0; i < m; i++) matrix[i][0] = 0;
  }
}

Time: O(m * n) — two full passes over the matrix. Space: O(1) — markers stored in the matrix itself.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript