← Back to index
MediumC3 min read

Set Matrix Zeroes

set entire row and column to zero when element is zero, using first row and column as markers for O(1) space.

matrixarrays

Problem link

View on LeetCode

Solutions in this repo

  • C../set-matrix-zeroes/solution.cC solution

use first row and first column as markers to track which rows/columns need to be zeroed. first check if first row and column themselves need clearing, then use them to mark other cells.

for cells [1..m-1][1..n-1], if cell is zero, mark matrix[r][0] = 0 and matrix[0][c] = 0. then in second pass, clear rows/columns based on these markers. finally clear first row/column if needed.

approach

  • check if first row/column need clearing (store flags)
  • use first row/column as markers for rest of matrix
  • clear rows/columns based on markers
  • clear first row/column if flags set

complexity

O(mn) time for three passes. O(1) space using matrix itself for markers.