Set Matrix Zeroes
Part of Practice: Matrix Choreography
Given an m x n matrix of integers, whenever a cell contains 0, set that cell's entire row and entire column to 0. Do it in place.
The catch is space: the easy version records which rows and columns need zeroing in two sets, costing O(m + n) extra memory. The follow-up every interviewer asks for is O(1) extra space — which forces you to store the markers inside the matrix itself.
Examples
- Input:
- matrix = [[1,1,1],[1,0,1],[1,1,1]]
- Output:
- [[1,0,1],[0,0,0],[1,0,1]]
The single 0 at row 1, column 1 wipes its row and its column.
- 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]]
Zeros at row 0, columns 0 and 3 wipe row 0 and both of those columns.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.