Matrix ZeroingLoading saved progress…

Matrix Zeroing

You're given an m × n matrix of numbers. Wherever a cell holds a 0, that zero "infects" its entire row and its entire column — every cell in that row and that column must become 0 too. Your job is to apply this rule across the whole matrix and return the result. This is the classic Set Matrix Zeroes problem; the catch is that only the zeros present in the original matrix trigger the rule.

Signature

// matrix: number[][] — an m×n grid (m rows, n columns)
// returns the same matrix, mutated in place, with rows and columns zeroed.
function matrixZeroing(matrix: number[][]): number[][];

Examples

A single zero zeroes its row and its column, and nothing else:

matrixZeroing([
  [1, 2, 3],
  [4, 0, 6],
  [7, 8, 9],
]);
// → [
//   [1, 0, 3],   // column 1 cleared
//   [0, 0, 0],   // row 1 cleared
//   [7, 0, 9],   // column 1 cleared
// ]

Two zeros each clear their own row and column; the cleared regions overlap:

matrixZeroing([
  [0, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 1, 0, 2],
]);
// → [
//   [0, 0, 0, 0],   // row 0 cleared (and col 0, col 2)
//   [0, 6, 0, 8],   // col 0 and col 2 cleared
//   [0, 0, 0, 0],   // row 2 cleared (and col 0, col 2)
// ]

Notes

  • In place — mutate the input array and return the same reference. Callers may rely on the original array being updated, not a copy.
  • Only original zeros trigger. A cell that becomes 0 because of the rule must NOT go on to zero its own row and column. Only the zeros present in the matrix you were handed count.
  • Each original zero clears a full row AND a full column — both, not one or the other.
  • The cascade trap — if you zero rows and columns as you scan, the zeros you write get re-read by later iterations and trigger more zeroing, eventually wiping the whole matrix. Decide what to clear before you clear anything.
  • Empty or degenerate input[], [[]], a single row, a single column, and a 1 × 1 matrix must all be handled without throwing.
Loading editor…