Set Matrix Zeroes - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

The goal is to modify the matrix in place so that if any cell contains 0, its entire row and column are set to 0. To avoid using extra space, we repurpose the first row and first column as markers. Two boolean flags — firstRowHasZero and firstColHasZero — are needed to preserve whether the first row or column originally contained any zeros, since these will later serve as marker storage and might otherwise lose their original information.

  • Step 1 — Scan & Mark:
    Traverse all cells of the matrix. Whenever a 0 is found at position (r, c):
    • If r === 0, set firstRowHasZero = true; otherwise mark the row by setting matrix[r][0] = 0.
    • If c === 0, set firstColHasZero = true; otherwise mark the column by setting matrix[0][c] = 0.
    Using the first row and column as markers is safe because writing a 0 there means the entire corresponding row or column will eventually be zeroed out — including that cell itself. The two boolean flags, firstRowHasZero and firstColHasZero, ensure that we remember whether the first row or column themselves originally contained a 0 and therefore need to be cleared at the end.
  • Step 2 — Zero Inner Cells Using Markers:
    For all cells (r, c) with r ≥ 1 and c ≥ 1, set matrix[r][c] = 0 if either matrix[r][0] === 0 or matrix[0][c] === 0, meaning that the corresponding row or column was marked earlier.
  • Step 3 — Zero First Row (if needed):
    If firstRowHasZero is true, set every cell in the first row to 0.
  • Step 4 — Zero First Column (if needed):
    If firstColHasZero is true, set every cell in the first column to 0.

This approach ensures all rows and columns are zeroed correctly without using extra arrays. The algorithm runs in O(m × n) time since every cell is visited at most twice, and uses only O(1) additional space for the two boolean flags besides the matrix itself.

Time Complexity

The whole matrix is scanned twice, and the first row and first column are scanned at most once. Therefore, the time complexity is O(m × n), where m is the number of rows and n is the number of columns.

Space Complexity

Only two boolean variables (firstRowHasZero and firstColHasZero) are used for tracking, so the algorithm requires constant extra space. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Set Matrix Zeroes coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/set-matrix-zeroes.