diff --git a/coin-change/Leo.py b/coin-change/Leo.py new file mode 100644 index 000000000..4712ddef5 --- /dev/null +++ b/coin-change/Leo.py @@ -0,0 +1,16 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + result = [amount + 1] * (amount + 1) + result[0] = 0 + + for i in range(1, amount + 1): + for c in coins: + if i >= c: + result[i] = min(result[i], result[i - c] + 1) + + if result[amount] == amount + 1: + return -1 + + return result[amount] + + ## TC: O(n * len(coins)) , SC: O(n), where n denotes amount diff --git a/decode-ways/Leo.py b/decode-ways/Leo.py new file mode 100644 index 000000000..b26b73bae --- /dev/null +++ b/decode-ways/Leo.py @@ -0,0 +1,22 @@ +class Solution: + def numDecodings(self, s: str) -> int: + if not s or s[0] == "0": + return 0 + + n = len(s) + dp = [0] * (n + 1) + dp[0], dp[1] = 1, 1 + + for i in range(2, n + 1): + one = int(s[i - 1]) + two = int(s[i - 2:i]) + + if 1 <= one <= 9: + dp[i] += dp[i - 1] + + if 10 <= two <= 26: + dp[i] += dp[i - 2] + + return dp[n] + + ## TC: O(n), SC: O(1) diff --git a/maximum-product-subarray/Leo.py b/maximum-product-subarray/Leo.py new file mode 100644 index 000000000..f08588d02 --- /dev/null +++ b/maximum-product-subarray/Leo.py @@ -0,0 +1,14 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + curMax, curMin = 1, 1 + res = nums[0] + + for n in nums: + vals = (n, n * curMax, n * curMin) + curMax, curMin = max(vals), min(vals) + + res = max(res, curMax) + + return res + + ## TC: O(n), SC: O(1) diff --git a/palindromic-substrings/Leo.py b/palindromic-substrings/Leo.py new file mode 100644 index 000000000..9fb58c8f9 --- /dev/null +++ b/palindromic-substrings/Leo.py @@ -0,0 +1,19 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + result = 0 + + def helper(left, right): + count = 0 + while left >= 0 and right < len(s) and s[left] == s[right]: + count += 1 + left -= 1 + right += 1 + return count + + for i in range(len(s)): + result += helper(i, i) + result += helper(i, i + 1) + + return result + + ## TC: O(n^2), SC: O(1) diff --git a/word-break/Leo.py b/word-break/Leo.py new file mode 100644 index 000000000..495dbc4f2 --- /dev/null +++ b/word-break/Leo.py @@ -0,0 +1,13 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + dp = [True] + [False] * len(s) + + for i in range(1, len(s) + 1): + for w in wordDict: + if i - len(w) >= 0 and dp[i - len(w)] and s[:i].endswith(w): + dp[i] = True + + return dp[-1] + + ## TC: O(len(str) * len(wordDict) * len(avg(wordDict[n]))) + ## SC: O(n)