-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergedTwo_SortedList_Day42.py
More file actions
81 lines (64 loc) · 2.07 KB
/
Copy pathMergedTwo_SortedList_Day42.py
File metadata and controls
81 lines (64 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#Brute Approach
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
arr = []
while list1:
arr.append(list1.val)
list1 = list1.next
while list2:
arr.append(list2.val)
list2 = list2.next
arr.sort()
dummy = ListNode()
curr = dummy
for val in arr:
curr.next = ListNode(val)
curr = curr.next
return dummy.next
# Time Complexity:
# Collecting values: O(n + m)
# Sorting: O((n + m) * log(n + m))
# Creating new list: O(n + m)
# Total: O((n + m) * log(n + m))
# Space Complexity: O(n + m) (for the array)
#Better Approach
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val < list2.val:
tail.next = ListNode(list1.val)
list1 = list1.next
else:
tail.next = ListNode(list2.val)
list2 = list2.next
tail = tail.next
while list1:
tail.next = ListNode(list1.val)
list1 = list1.next
tail = tail.next
while list2:
tail.next = ListNode(list2.val)
list2 = list2.next
tail = tail.next
return dummy.next
# Time Complexity: O(n + m)
# Space Complexity: O(n + m) (new list created)
#Optimal Approach
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
tail = dummy
while list1 and list2:
if list1.val < list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
tail.next = list1 if list1 else list2
return dummy.next
# Time Complexity: O(n + m)
# Space Complexity: O(1) (in-place)