Set Matrix Zeroes
Difficulty: Medium · Pattern: Matrix · LeetCode #73
If an element is 0, set its entire row and column to 0. Do it in place. Follow-up: use O(1) extra space.
Examples
text
[[1,1,1], [[1,0,1],
[1,0,1], → [0,0,0],
[1,1,1]] [1,0,1]]
[[0,1,2,0],[3,4,5,2],[1,3,1,5]] → [[0,0,0,0],[0,4,5,0],[0,3,1,0]]Hints
- Zeroing as soon as you find a 0 creates new zeros that then spread wrongly. Record first, zero later.
- O(m+n) space: two boolean arrays. O(1) space: store those markers in the first row and first column.
Approach
col0 = any(matrix[r][0] == 0). Column 0's marker needs its own flag, becausematrix[0][0]is shared with row 0.- For each cell
(r, c≥1)that's 0: markmatrix[r][0] = 0andmatrix[0][c] = 0. - Bottom-up, right-to-left over
c ≥ 1: zero the cell if its row marker or column marker is 0. Then zeromatrix[r][0]ifcol0.
Processing bottom-up keeps row 0's markers intact until the very end. That's O(mn) time and O(1) space. Getting the marker/order details right is the whole interview.
Complexity
Time: O(m·n). Space: O(1) with the markers (O(m+n) with sets).
Python solution
def setZeroes(matrix):
R, C = len(matrix), len(matrix[0])
col0 = False
for r in range(R):
if matrix[r][0] == 0:
col0 = True
for c in range(1, C):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(R - 1, -1, -1):
for c in range(C - 1, 0, -1):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if col0:
matrix[r][0] = 0JavaScript solution
function setZeroes(matrix) {
const R = matrix.length, C = matrix[0].length, rows = new Set(), cols = new Set();
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (matrix[r][c] === 0) { rows.add(r); cols.add(c); }
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (rows.has(r) || cols.has(c)) matrix[r][c] = 0;
}