codejump
MediumPro challengePythonJavaScriptTypeScript

Matrix — Set Matrix Zeroes

AlgorithmsMatrixArrays

solve(matrix) — if a cell is 0, set its entire row and entire column to 0. Do
it in place and return the matrix. Only the zeros that were in the *original* matrix
count: the zeros you create must not spread further.

A copy of the matrix or two boolean arrays costs O(rows + cols) space. For O(1) extra
space, use the first row and the first column of the matrix itself as the markers: if
matrix[r][c] is zero, record it in matrix[r][0] and matrix[0][c]. Two booleans remember
whether the first row and the first column originally contained a zero.

Examples

solve([[1,1,1],[1,0,1],[1,1,1]])      → [[1,0,1],[0,0,0],[1,0,1]]
solve([[0,1,2,0],[3,4,5,2],[1,3,1,5]]) → [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

Sample tests

Test #1Zero in the middle
Input: [[[1,1,1],[1,0,1],[1,1,1]]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Test #2Zeros on the first row
Input: [[[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]]
Test #3No zeros
Input: [[[1,2],[3,4]]]
Output: [[1,2],[3,4]]