73. Set Matrix Zeroes
Asked at 19Bloomberg58Meta57Microsoft56Amazon55Google51Apple35tcs46Nykaa89eBay77ZScaler73Walmart Labs60Zoho60Nutanix60Autodesk59Nvidia48Juspay47Infosys39Oracle35Goldman Sachs33
Problem
Wherever matrix has a 0, set that cell's entire row and column to 0, in place.
Example: [[0,1,2,0],[3,4,5,2],[1,3,1,5]] → [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
Constraints: follow-up: O(1) extra space.
Use row 0 and column 0 as zero-flags for their rows/columns; remember separately whether row 0 / col 0 themselves need zeroing.
Complexity: O(m·n) time, O(1) space.
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
R, C = len(matrix), len(matrix[0])
row0 = any(matrix[0][c] == 0 for c in range(C))
col0 = any(matrix[r][0] == 0 for r in range(R))
for r in range(1, R):
for c in range(1, C):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(1, R):
for c in range(1, C):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if row0:
for c in range(C):
matrix[0][c] = 0
if col0:
for r in range(R):
matrix[r][0] = 0
m = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]; Solution().setZeroes(m)
assert m == [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
m = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]; Solution().setZeroes(m)
assert m == [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
class Solution {
public void setZeroes(int[][] matrix) {
int R = matrix.length, C = matrix[0].length;
boolean row0 = false, col0 = false;
for (int c = 0; c < C; c++) if (matrix[0][c] == 0) row0 = true;
for (int r = 0; r < R; r++) if (matrix[r][0] == 0) col0 = true;
for (int r = 1; r < R; r++)
for (int c = 1; c < C; c++) if (matrix[r][c] == 0) matrix[r][0] = matrix[0][c] = 0;
for (int r = 1; r < R; r++)
for (int c = 1; c < C; c++) if (matrix[r][0] == 0 || matrix[0][c] == 0) matrix[r][c] = 0;
if (row0) Arrays.fill(matrix[0], 0);
if (col0) for (int r = 0; r < R; r++) matrix[r][0] = 0;
}
}
func setZeroes(matrix [][]int) {
R, C := len(matrix), len(matrix[0])
row0, col0 := false, false // the first row/column are reused as markers, so remember them
for c := 0; c < C; c++ {
row0 = row0 || matrix[0][c] == 0
}
for r := 0; r < R; r++ {
col0 = col0 || matrix[r][0] == 0
}
for r := 1; r < R; r++ {
for c := 1; c < C; c++ {
if matrix[r][c] == 0 {
matrix[r][0], matrix[0][c] = 0, 0
}
}
}
for r := 1; r < R; r++ {
for c := 1; c < C; c++ {
if matrix[r][0] == 0 || matrix[0][c] == 0 {
matrix[r][c] = 0
}
}
}
if row0 {
for c := 0; c < C; c++ {
matrix[0][c] = 0
}
}
if col0 {
for r := 0; r < R; r++ {
matrix[r][0] = 0
}
}
}