diff --git a/coin-change/jeldo.py b/coin-change/jeldo.py new file mode 100644 index 000000000..227a542db --- /dev/null +++ b/coin-change/jeldo.py @@ -0,0 +1,10 @@ +class Solution: + # O(n*m), n = len(coins), m = amount + def coinChange(self, coins: list[int], amount: int) -> int: + dp = [amount+1] * (amount+1) + dp[0] = 0 + for i in range(amount+1): + for coin in coins: + if i - coin >= 0: + dp[i] = min(dp[i], dp[i-coin]+1) + return dp[amount] if dp[amount] != amount+1 else -1 diff --git a/merge-two-sorted-lists/jeldo.py b/merge-two-sorted-lists/jeldo.py new file mode 100644 index 000000000..371c9ba69 --- /dev/null +++ b/merge-two-sorted-lists/jeldo.py @@ -0,0 +1,17 @@ +class Solution: + # O(n+m), n = len(list1), m = len(list2) + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + head = node = ListNode() + while list1 and list2: + if list1.val <= list2.val: + node.next = list1 + list1 = list1.next + else: + node.next = list2 + list2 = list2.next + node = node.next + if list1: + node.next = list1 + if list2: + node.next = list2 + return head.next diff --git a/missing-number/jeldo.py b/missing-number/jeldo.py new file mode 100644 index 000000000..67976636b --- /dev/null +++ b/missing-number/jeldo.py @@ -0,0 +1,5 @@ +class Solution: + # O(n), n = len(nums) + def missingNumber(self, nums: List[int]) -> int: + n = len(nums) + return n*(n+1)//2 - sum(nums) diff --git a/word-search/jeldo.py b/word-search/jeldo.py new file mode 100644 index 000000000..06e04e833 --- /dev/null +++ b/word-search/jeldo.py @@ -0,0 +1,29 @@ +class Solution: + # O(m*n), m*n = board's width,heigh + def exist(self, board: List[List[str]], word: str) -> bool: + dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] + result = False + + def dfs(i, j, visited, w): + nonlocal result + if (i, j) in visited: + return + if not (0 <= i < len(board)) or not (0 <= j < len(board[0])): + return + w += board[i][j] + if not (word[:len(w)] == w): + return + visited.add((i, j)) + if w == word: + result = True + return + for d in dirs: + dfs(i + d[0], j + d[1], visited, w) + visited.remove((i, j)) # backtracking + + for i in range(len(board)): + for j in range(len(board[0])): + dfs(i, j, set(), "") + if result: + return True + return False