set-matrix-zeroes.sh — zsh
matrixarrays

Given an m x n integer matrix, if a cell contains 0, set its entire row and column to 0. Return the modified matrix.

Input / output

  • Input: matrix: int[][]
  • Output: int[][] (the modified matrix)

Examples

  1. matrix = [[1,1,1],[1,0,1],[1,1,1]] returns [[1,0,1],[0,0,0],[1,0,1]].
  2. matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] returns [[0,0,0,0],[0,4,5,0],[0,3,1,0]].
  3. matrix = [[1]] returns [[1]] (no zero present).

Constraints

  • 1 <= matrix.length, matrix[0].length <= 200
  • -2^31 <= matrix[i][j] <= 2^31 - 1

Follow-up Can you do it using O(1) extra space by reusing the first row and first column of the matrix itself as marker storage, instead of allocating separate row/column tracking sets?

Examples
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,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Example 3 (no zero, single cell)
Input: matrix = [[1]]
Output: [[1]]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.