|
| 1 | +''' |
| 2 | +# 73. Set Matrix Zeroes |
| 3 | +# solution reference: https://www.algodale.com/problems/set-matrix-zeroes/ |
| 4 | +''' |
| 5 | +class Solution: |
| 6 | + ''' |
| 7 | + ### TC is O(m * n): |
| 8 | + - iterating through every cells, to find the zero cells. = O(m * n) 1️⃣ |
| 9 | + - iterating through every cells, to update the rows. = O(m * n) 2️⃣ |
| 10 | + - iterating through every cells, to update the columns. = O(m * n) 3️⃣ |
| 11 | +
|
| 12 | + ### SC is O(m + n): |
| 13 | + - using each set to store the rows(O(m)) and columns(O(n)) that have zero. = O(m + n) |
| 14 | + ''' |
| 15 | + def setZeroesWithSet(self, matrix: List[List[int]]) -> None: |
| 16 | + zero_rows = set() # SC: O(m) |
| 17 | + zero_cols = set() # SC: O(n) |
| 18 | + |
| 19 | + for r in range(len(matrix)): # TC: O(m * n) |
| 20 | + for c in range(len(matrix[0])): |
| 21 | + if matrix[r][c] == 0: |
| 22 | + zero_rows.add(r) |
| 23 | + zero_cols.add(c) |
| 24 | + |
| 25 | + for r in zero_rows: # TC: O(m * n) |
| 26 | + for i in range(len(matrix[0])): |
| 27 | + matrix[r][i] = 0 |
| 28 | + |
| 29 | + for c in zero_cols: # TC: O(m * n) |
| 30 | + for i in range(len(matrix)): |
| 31 | + matrix[i][c] = 0 |
| 32 | + |
| 33 | + ''' |
| 34 | + ### TC is O(m * n): |
| 35 | + - check if the first row or column has zero. = O(m + n) |
| 36 | + - iterating through every cells, if it has zero, mark the first row and column. = O(m * n) 1️⃣ |
| 37 | + - update the matrix based on the marks(0) in the first row and column. = O(m * n) 2️⃣ |
| 38 | + - if the first row or column has zero, iterating through every cells, in the first row or column and updating it. = O(m + n) |
| 39 | +
|
| 40 | + ### SC is O(1): |
| 41 | + - using the first_row_has_zero and first_col_has_zero to store the zero information. = O(1) |
| 42 | + ''' |
| 43 | + def setZeroesWithMarkerAndVariable(self, matrix: List[List[int]]) -> None: |
| 44 | + rows = len(matrix) |
| 45 | + cols = len(matrix[0]) |
| 46 | + |
| 47 | + first_row_has_zero = any(matrix[0][j] == 0 for j in range(cols)) # TC: O(n), SC: O(1) |
| 48 | + first_col_has_zero = any(matrix[i][0] == 0 for i in range(rows)) # TC: O(m), SC: O(1) |
| 49 | + |
| 50 | + for r in range(1, rows): # TC: O(m * n) |
| 51 | + for c in range(1, cols): |
| 52 | + if matrix[r][c] == 0: |
| 53 | + matrix[r][0] = 0 |
| 54 | + matrix[0][c] = 0 |
| 55 | + |
| 56 | + for r in range(1, rows): # TC: O(m * n) |
| 57 | + for c in range(1, cols): |
| 58 | + if matrix[r][0] == 0 or matrix[0][c] == 0: |
| 59 | + matrix[r][c] = 0 |
| 60 | + |
| 61 | + if first_row_has_zero: |
| 62 | + for c in range(cols): # TC: O(n) |
| 63 | + matrix[0][c] = 0 |
| 64 | + |
| 65 | + if first_col_has_zero: |
| 66 | + for r in range(rows): # TC: O(m) |
| 67 | + matrix[r][0] = 0 |
0 commit comments