|
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. |
| 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. |
14 | 16 | Runtime: O(M * N)
|
15 |
| - Space Complexity: O(min(M, N)) |
| 17 | + Space Complexity: O(M * N) - worst case, input matrix has all zero values |
16 | 18 | :param matrix: an MxN matrix. M is the number of rows, N is the number of columns
|
17 | 19 | :return: a zero-modified matrix
|
18 | 20 | """
|
19 | 21 | M = len(matrix)
|
20 | 22 | N = len(matrix[0])
|
21 | 23 |
|
22 |
| - zeroed_rows = set() |
23 |
| - zeroed_cols = set() |
24 |
| - |
| 24 | + zero_coordinates = [] |
| 25 | + # first, scan for coordinates of 0s |
25 | 26 | for i, row in enumerate(matrix):
|
26 | 27 | for j, num in enumerate(row):
|
27 |
| - if num != 0 or i in zeroed_rows or j in zeroed_cols: |
| 28 | + if num != 0: |
28 | 29 | continue
|
29 |
| - # otherwise, set row to 0 by looping through columns of current row |
30 |
| - for k in range(N): |
31 |
| - matrix[i][k] = 0 |
32 |
| - # set column to 0 by looping through rows of current column |
33 |
| - for l in range(M): |
34 |
| - matrix[l][j] = 0 |
35 |
| - # update zeroed row and col sets |
36 |
| - zeroed_cols.add(j) |
37 |
| - zeroed_rows.add(i) |
38 |
| - break |
| 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: |
| 34 | + # set row to 0 by looping through columns of current row |
| 35 | + for k in range(N): |
| 36 | + matrix[i][k] = 0 |
| 37 | + # set column to 0 by looping through rows of current column |
| 38 | + for l in range(M): |
| 39 | + matrix[l][j] = 0 |
39 | 40 | return matrix
|
40 | 41 |
|
41 | 42 |
|
|
0 commit comments