Using Extra Sets
Intuition
The most straightforward approach is to first scan the matrix and record which rows and columns contain a zero. Use two sets: one for rows and one for columns. Then make a second pass through the matrix: if the current cell's row or column is in the respective set, set that cell to zero.
Algorithm
- Initialize two sets: zeroRows and zeroCols.
- Iterate through every cell of the matrix. If matrix[i][j] == 0, add i to zeroRows and j to zeroCols.
- Iterate through every cell again. If i is in zeroRows or j is in zeroCols, set matrix[i][j] to 0.
O(m * n)SpaceO(m + n)Code (C++ · Java · Python · Go)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
unordered_set<int> zeroRows, zeroCols;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
zeroRows.insert(i);
zeroCols.insert(j);
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (zeroRows.count(i) || zeroCols.count(j)) {
matrix[i][j] = 0;
}
}
}
}
};class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
Set<Integer> zeroRows = new HashSet<>();
Set<Integer> zeroCols = new HashSet<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
zeroRows.add(i);
zeroCols.add(j);
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (zeroRows.contains(i) || zeroCols.contains(j)) {
matrix[i][j] = 0;
}
}
}
}
}def setZeroes(matrix: list[list[int]]) -> None:
m, n = len(matrix), len(matrix[0])
zero_rows = set()
zero_cols = set()
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
zero_rows.add(i)
zero_cols.add(j)
for i in range(m):
for j in range(n):
if i in zero_rows or j in zero_cols:
matrix[i][j] = 0func setZeroes(matrix [][]int) {
m, n := len(matrix), len(matrix[0])
zeroRows := make(map[int]bool)
zeroCols := make(map[int]bool)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == 0 {
zeroRows[i] = true
zeroCols[j] = true
}
}
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if zeroRows[i] || zeroCols[j] {
matrix[i][j] = 0
}
}
}
}