CodeSpeek

Set Matrix Zeroes

Medium · Math & Geometry

You are given a 2D grid of integers. Whenever a cell contains a zero, every other cell in its entire row and its entire column must also be turned into zero. Modify the grid in place to reflect this rule and do not return anything.

Examples

Input:  matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]
Why:    The single zero at row 1, column 1 wipes out the rest of row 1 and the rest of column 1.
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]]
Why:    Zeroes at (0,0) and (0,3) clear row 0 entirely, and clearing columns 0 and 3 also propagates because (0,0) is itself zero, so column 0 is cleared in every row.
Input:  matrix = [[1,2],[3,4]]
Output: [[1,2],[3,4]]
Why:    There are no zero cells, so nothing changes.

Constraints

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

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Set Matrix Zeroes

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Set Matrix Zeroes. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.