|
10 | 10 | def zero_matrix(matrix: List[List[int]]) -> List[List[int]]:
|
11 | 11 | """
|
12 | 12 | zero_matrix will take in an MxN matrix and when a 0 element is found, the whole column and row
|
13 |
| - will be set to 0. The algorithm works by first scanning for coordinates where there are 0s and |
14 |
| - storing those coordinates. |
15 |
| - Then we go through each coordinate and set the row and column at that coordinate equal to 0. |
| 13 | + will be set to 0. The algorithm works by first scanning for rows and columns where there is a 0 |
| 14 | + and store into a set. |
| 15 | + Then we go through each stored row and column indices and proceed to set the rows and columns to 0. |
16 | 16 | Runtime: O(M * N)
|
17 |
| - Space Complexity: O(M * N) - worst case, input matrix has all zero values |
| 17 | + Space Complexity: O(M + N) |
18 | 18 | :param matrix: an MxN matrix. M is the number of rows, N is the number of columns
|
19 | 19 | :return: a zero-modified matrix
|
20 | 20 | """
|
21 | 21 | M = len(matrix)
|
22 | 22 | N = len(matrix[0])
|
23 | 23 |
|
24 |
| - zero_coordinates = [] |
| 24 | + rows_to_zero = set() |
| 25 | + cols_to_zero = set() |
25 | 26 | # first, scan for coordinates of 0s
|
26 | 27 | for i, row in enumerate(matrix):
|
27 | 28 | for j, num in enumerate(row):
|
28 | 29 | if num != 0:
|
29 | 30 | continue
|
30 |
| - # otherwise, save the coordinate |
31 |
| - zero_coordinates.append((i, j)) |
32 |
| - # then, set row and col to zero of each coordinate |
33 |
| - for i, j in zero_coordinates: |
| 31 | + # otherwise, save row or col to rows or cols to zero set |
| 32 | + rows_to_zero.add(i) |
| 33 | + cols_to_zero.add(j) |
| 34 | + for i in rows_to_zero: |
34 | 35 | # set row to 0 by looping through columns of current row
|
35 | 36 | for k in range(N):
|
36 | 37 | matrix[i][k] = 0
|
| 38 | + |
| 39 | + for j in cols_to_zero: |
37 | 40 | # set column to 0 by looping through rows of current column
|
38 | 41 | for l in range(M):
|
39 | 42 | matrix[l][j] = 0
|
@@ -167,6 +170,10 @@ def setUp(self):
|
167 | 170 | [0, 0, 0, 0],
|
168 | 171 | [0, 0, 0, 0]
|
169 | 172 | ]
|
| 173 | + ), |
| 174 | + ( |
| 175 | + [[0] * 1000 for _ in range(1000)], |
| 176 | + [[0] * 1000 for _ in range(1000)], |
170 | 177 | )
|
171 | 178 | ]
|
172 | 179 |
|
|
0 commit comments