Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

O(mn) time O(m + n) space two pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public void setZeroes(int[][] matrix) {
HashSet<Integer> rows = new HashSet<>();
HashSet<Integer> cols = new HashSet<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
rows.add(i);
cols.add(j);
}
}
}

for (int row : rows) {
for (int i = 0; i < matrix[0].length; i++) {
if (matrix[row][i] != 0) {
matrix[row][i] = 0;
}
}
}

for (int col : cols) {
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][col] != 0) {
matrix[i][col] = 0;
}
}
}
}
}

O(mn) time O(1) space two pass solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Solution {
public void setZeroes(int[][] matrix) {
int col0 = 1;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i][0] == 0) {
col0 = 0;
}
for (int j = 1; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}

// start from right bottom corner
// if start from left upper corner, must start from (1,1)
// the first column should be set only after setting
// the rest matrix
for (int i = matrix.length - 1; i >= 0; i--) {
for (int j = matrix[0].length - 1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
if (col0 == 0) {
matrix[i][0] = 0;
}
}
}
}