This approach uses two additional arrays to track the rows and columns that need to be zeroed.
- Traverse the matrix and mark rows and columns that need to be zeroed.
- Then, update the matrix based on the values in these arrays.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for the additional arrays.
1def setZeroes(matrix):
2 m, n = len(matrix), len(matrix[0])
3 row = [False] * m
4 col = [False] * n
5
6 for i in range(m):
7 for j in range(n):
8 if matrix[i][j] == 0:
9 row[i] = True
10 col[j] = True
11
12 for i in range(m):
13 for j in range(n):
14 if row[i] or col[j]:
15 matrix[i][j] = 0
This approach uses the matrix itself to track zeroes.
- Use the first row and column as markers.
- Traverse the matrix and if an element is zero, mark its row and column.
- Traverse again and set matrix elements to zero based on marked rows and columns.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1) since the algorithm runs in constant space.
1function setZeroes(matrix) {
2 let m = matrix.length;
3 let n = matrix[0].length;
4 let col0 = 1;
5 for (let i = 0; i < m; i++) {
6 if (matrix[i][0] === 0) col0 = 0;
7 for (let j = 1; j < n; j++) {
8 if (matrix[i][j] === 0) {
9 matrix[i][0] = 0;
10 matrix[0][j] = 0;
11 }
12 }
13 }
14
15 for (let i = 1; i < m; i++) {
16 for (let j = 1; j < n; j++) {
17 if (matrix[i][0] === 0 || matrix[0][j] === 0) {
18 matrix[i][j] = 0;
19 }
20 }
21 }
22
23 if (matrix[0][0] === 0) {
24 for (let j = 0; j < n; j++) {
25 matrix[0][j] = 0;
26 }
27 }
28
29 if (col0 === 0) {
30 for (let i = 0; i < m; i++) {
31 matrix[i][0] = 0;
32 }
33 }
34}