Skip to content

Commit cbe1e32

Browse files
committed
add test case, update solution
1 parent 870abc8 commit cbe1e32

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

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

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,30 +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. 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.
1616
Runtime: O(M * N)
17-
Space Complexity: O(M * N) - worst case, input matrix has all zero values
17+
Space Complexity: O(M + N)
1818
:param matrix: an MxN matrix. M is the number of rows, N is the number of columns
1919
:return: a zero-modified matrix
2020
"""
2121
M = len(matrix)
2222
N = len(matrix[0])
2323

24-
zero_coordinates = []
24+
rows_to_zero = set()
25+
cols_to_zero = set()
2526
# first, scan for coordinates of 0s
2627
for i, row in enumerate(matrix):
2728
for j, num in enumerate(row):
2829
if num != 0:
2930
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:
3435
# set row to 0 by looping through columns of current row
3536
for k in range(N):
3637
matrix[i][k] = 0
38+
39+
for j in cols_to_zero:
3740
# set column to 0 by looping through rows of current column
3841
for l in range(M):
3942
matrix[l][j] = 0
@@ -167,6 +170,10 @@ def setUp(self):
167170
[0, 0, 0, 0],
168171
[0, 0, 0, 0]
169172
]
173+
),
174+
(
175+
[[0] * 1000 for _ in range(1000)],
176+
[[0] * 1000 for _ in range(1000)],
170177
)
171178
]
172179

0 commit comments

Comments
 (0)