Set Matrix Zeroes Easy 0 attempts
LeetCode ↗

Set Matrix Zeroes

Easy ArrayTwo Pointers LeetCode

You're given an m x n integer matrix. Whenever a cell holds the value 0, every other cell in that cell's row and every cell in its column must also become 0. Apply these changes directly to the given matrix.

Using O(m + n) extra space to remember which rows and columns to zero out is the straightforward route — the harder version of this problem is pulling it off with only O(1) extra space.

Input Format
Implement setZeroes(matrix). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Modify argument 1 in place. The editor compares its final value; the function return value is ignored.

Sample Input and Output

Example 1 · Run Sample

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
Test Cases (2)
Case 1
Args: [[[1,1,1],[1,0,1],[1,1,1]]] Expected: [[1,0,1],[0,0,0],[1,0,1]]
Case 2
Args: [[[0,1],[2,3]]] Expected: [[0,0],[0,3]]

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 a dedicated flag 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.

Saved in this browser only. Private to you.

JavaScript