Skip to content

Commit 80a15c7

Browse files
authored
Merge pull request #2480 from jylee2033/main
[jylee2033] WEEK 04 solutions
2 parents 00dcd6e + 4c9df25 commit 80a15c7

3 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def findMin(self, nums: List[int]) -> int:
3+
# Binary Search: compare mid with right
4+
# nums[mid] > nums[right] -> min is in right half
5+
# nums[mid] < nums[right] -> min is in left half (including mid)
6+
7+
left = 0
8+
right = len(nums) - 1
9+
10+
while left < right:
11+
mid = (left + right) // 2
12+
13+
if nums[mid] > nums[right]:
14+
left = mid + 1
15+
elif nums[mid] < nums[right]:
16+
right = mid
17+
18+
return nums[left]
19+
20+
# Time Complexity: O(log n)
21+
# Space Complexity: O(1)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def maxDepth(self, root: Optional[TreeNode]) -> int:
9+
# Recursive approach
10+
11+
if not root:
12+
return 0
13+
14+
left_depth = self.maxDepth(root.left)
15+
right_depth = self.maxDepth(root.right)
16+
17+
return max(left_depth, right_depth) + 1
18+
19+
# Time Complexity: O(n)
20+
# Space Complexity: O(n)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
# Use a while loop to compare values and build the merged list
9+
10+
# Create a new list
11+
output = ListNode()
12+
cur = output
13+
14+
while list1 and list2:
15+
if list1.val < list2.val:
16+
cur.next = list1
17+
list1 = list1.next
18+
else:
19+
cur.next = list2
20+
list2 = list2.next
21+
22+
cur = cur.next
23+
24+
# Attach the remaining nodes
25+
cur.next = list1 or list2
26+
27+
return output.next
28+
29+
# Time Complexity : O(n + m), n - lenght of list1, m - length of list2
30+
# Space Complexity : O(1)

0 commit comments

Comments
 (0)