File tree Expand file tree Collapse file tree 5 files changed +84
-0
lines changed Expand file tree Collapse file tree 5 files changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def coinChange (self , coins : List [int ], amount : int ) -> int :
3
+ result = [amount + 1 ] * (amount + 1 )
4
+ result [0 ] = 0
5
+
6
+ for i in range (1 , amount + 1 ):
7
+ for c in coins :
8
+ if i >= c :
9
+ result [i ] = min (result [i ], result [i - c ] + 1 )
10
+
11
+ if result [amount ] == amount + 1 :
12
+ return - 1
13
+
14
+ return result [amount ]
15
+
16
+ ## TC: O(n * len(coins)) , SC: O(n), where n denotes amount
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def numDecodings (self , s : str ) -> int :
3
+ if not s or s [0 ] == "0" :
4
+ return 0
5
+
6
+ n = len (s )
7
+ dp = [0 ] * (n + 1 )
8
+ dp [0 ], dp [1 ] = 1 , 1
9
+
10
+ for i in range (2 , n + 1 ):
11
+ one = int (s [i - 1 ])
12
+ two = int (s [i - 2 :i ])
13
+
14
+ if 1 <= one <= 9 :
15
+ dp [i ] += dp [i - 1 ]
16
+
17
+ if 10 <= two <= 26 :
18
+ dp [i ] += dp [i - 2 ]
19
+
20
+ return dp [n ]
21
+
22
+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxProduct (self , nums : List [int ]) -> int :
3
+ curMax , curMin = 1 , 1
4
+ res = nums [0 ]
5
+
6
+ for n in nums :
7
+ vals = (n , n * curMax , n * curMin )
8
+ curMax , curMin = max (vals ), min (vals )
9
+
10
+ res = max (res , curMax )
11
+
12
+ return res
13
+
14
+ ## TC: O(n), SC: O(1)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def countSubstrings (self , s : str ) -> int :
3
+ result = 0
4
+
5
+ def helper (left , right ):
6
+ count = 0
7
+ while left >= 0 and right < len (s ) and s [left ] == s [right ]:
8
+ count += 1
9
+ left -= 1
10
+ right += 1
11
+ return count
12
+
13
+ for i in range (len (s )):
14
+ result += helper (i , i )
15
+ result += helper (i , i + 1 )
16
+
17
+ return result
18
+
19
+ ## TC: O(n^2), SC: O(1)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
3
+ dp = [True ] + [False ] * len (s )
4
+
5
+ for i in range (1 , len (s ) + 1 ):
6
+ for w in wordDict :
7
+ if i - len (w ) >= 0 and dp [i - len (w )] and s [:i ].endswith (w ):
8
+ dp [i ] = True
9
+
10
+ return dp [- 1 ]
11
+
12
+ ## TC: O(len(str) * len(wordDict) * len(avg(wordDict[n])))
13
+ ## SC: O(n)
You can’t perform that action at this time.
0 commit comments