diff --git a/coin-change/i-mprovising.py b/coin-change/i-mprovising.py new file mode 100644 index 000000000..912f44c18 --- /dev/null +++ b/coin-change/i-mprovising.py @@ -0,0 +1,30 @@ +""" +Time complexity O(len(coins) * amount) +Space complexity O(amount) + +Dynamic programming +""" + +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + coins = sorted(coins) + + if amount == 0 : + return 0 + + dp = [0] + [-1 for _ in range(amount)] + + for i in range(coins[0], amount+1): + tmp = [] + for x in coins: + if i - x >= 0: + if dp[i - x] != -1: + tmp.append(dp[i - x] + 1) + if len(tmp) == 0: + dp[i] = -1 + else: + dp[i] = min(tmp) + + if dp[-1] == 0: + return -1 + return dp[-1] diff --git a/find-minimum-in-rotated-sorted-array/i-mprovising.py b/find-minimum-in-rotated-sorted-array/i-mprovising.py new file mode 100644 index 000000000..18e850cb7 --- /dev/null +++ b/find-minimum-in-rotated-sorted-array/i-mprovising.py @@ -0,0 +1,23 @@ +""" +Time complexity O(logn) +Space compexity O(1) + +Binary search +""" + +class Solution: + + def findMin(self, nums: List[int]) -> int: + start = 1 + end = len(nums) - 1 + + while start <= end: + mid = (start + end) // 2 + if nums[mid-1] > nums[mid]: + return nums[mid] + if nums[0] < nums[mid]: + start = mid + 1 + else: + end = mid - 1 + + return nums[0] diff --git a/maximum-depth-of-binary-tree/i-mprovising.py b/maximum-depth-of-binary-tree/i-mprovising.py new file mode 100644 index 000000000..0206b658e --- /dev/null +++ b/maximum-depth-of-binary-tree/i-mprovising.py @@ -0,0 +1,24 @@ +""" +Time complexity O(n) +""" +from collections import deque + +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + if not root: + return 0 + + max_depth = 0 + + # bfs + q = deque([[root, 1]]) + while(q): + node, depth = q.pop() + if max_depth < depth: + max_depth = depth + if node.left: + q.append([node.left, depth+1]) + if node.right: + q.append([node.right, depth+1]) + + return max_depth diff --git a/merge-two-sorted-lists/i-mprovising.py b/merge-two-sorted-lists/i-mprovising.py new file mode 100644 index 000000000..d898b7dc8 --- /dev/null +++ b/merge-two-sorted-lists/i-mprovising.py @@ -0,0 +1,35 @@ +""" +Time complexity O(n+m) +""" + +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + if not (list1 or list2): + return list1 or list2 # if empty list + + nums = [] + while(list1 or list2): + if not list1: + val = list2.val + list2 = list2.next + elif not list2: + val = list1.val + list1 = list1.next + else: + if list1.val <= list2.val: + val = list1.val + list1 = list1.next + else: + val = list2.val + list2 = list2.next + nums.append(val) + + head = ListNode(nums[0]) + node = head + if len(nums) == 1: + return head + for n in nums[1:]: + tmp = ListNode(n) + node.next = tmp + node = tmp + return head