File tree 1 file changed +34
-0
lines changed 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ # TC: O(m * n)
2
+ # SC: O(m * n)
3
+ class Solution :
4
+ def setZeroes (self , matrix : List [List [int ]]) -> None :
5
+ rows , cols = len (matrix ), len (matrix [0 ])
6
+ first_row_zero = any (matrix [0 ][j ] == 0 for j in range (cols ))
7
+ first_col_zero = any (matrix [i ][0 ] == 0 for i in range (rows ))
8
+
9
+ # Use first row and column to mark zero rows and columns
10
+ for i in range (1 , rows ):
11
+ for j in range (1 , cols ):
12
+ if matrix [i ][j ] == 0 :
13
+ matrix [i ][0 ] = matrix [0 ][j ] = 0
14
+
15
+ # Set rows to zero based on marks in the first column
16
+ for i in range (1 , rows ):
17
+ if matrix [i ][0 ] == 0 :
18
+ for j in range (1 , cols ):
19
+ matrix [i ][j ] = 0
20
+
21
+ # Set columns to zero based on marks in the first row
22
+ for j in range (1 , cols ):
23
+ if matrix [0 ][j ] == 0 :
24
+ for i in range (1 , rows ):
25
+ matrix [i ][j ] = 0
26
+
27
+ # Handle the first row and column separately if needed
28
+ if first_row_zero :
29
+ for j in range (cols ):
30
+ matrix [0 ][j ] = 0
31
+
32
+ if first_col_zero :
33
+ for i in range (rows ):
34
+ matrix [i ][0 ] = 0
You can’t perform that action at this time.
0 commit comments