Skip to content

Commit 870abc8

Browse files
committed
update to new solution
1 parent 720e811 commit 870abc8

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

Python/chapter01/1.8 - Zero Matrix/miguel_1.8_sol.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,33 @@
1010
def zero_matrix(matrix: List[List[int]]) -> List[List[int]]:
1111
"""
1212
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.
1416
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
1618
:param matrix: an MxN matrix. M is the number of rows, N is the number of columns
1719
:return: a zero-modified matrix
1820
"""
1921
M = len(matrix)
2022
N = len(matrix[0])
2123

22-
zeroed_rows = set()
23-
zeroed_cols = set()
24-
24+
zero_coordinates = []
25+
# first, scan for coordinates of 0s
2526
for i, row in enumerate(matrix):
2627
for j, num in enumerate(row):
27-
if num != 0 or i in zeroed_rows or j in zeroed_cols:
28+
if num != 0:
2829
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
3940
return matrix
4041

4142

0 commit comments

Comments
 (0)