File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 21. Merge Two Sorted Lists
3+
4+ A. iterative approach: use a temp node to store the result.
5+ B. recursive approach: use recursion to merge the two lists.
6+
7+
8+ ## Time and Space Complexity
9+
10+ ### A. Iterative Approach
11+
12+ ```
13+ TC: O(n + m)
14+ SC: O(1)
15+ ```
16+
17+ #### TC is O(n + m):
18+ - iterating through the two lists just once for merge two sorted lists. = O(n + m)
19+
20+ #### SC is O(1):
21+ - temp node is used to store the result. = O(1)
22+
23+ ### B. Recursive Approach
24+
25+ ```
26+ TC: O(n + m)
27+ SC: O(n + m)
28+ ```
29+
30+ #### TC is O(n + m):
31+ - iterating through the two lists just once for merge two sorted lists. = O(n + m)
32+
33+ #### SC is O(n + m):
34+ - because of the recursive call stack. = O(n + m)
35+ '''
36+ class Solution :
37+ '''
38+ A. Iterative Approach
39+ - use a temp node to store the result.
40+ - use a current node to iterate through the two lists.
41+ '''
42+ def mergeTwoListsIterative (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
43+ temp = ListNode (- 1 )
44+ current = temp
45+
46+ while list1 is not None and list2 is not None :
47+ if list1 .val < list2 .val :
48+ current .next = list1
49+ list1 = list1 .next
50+ else :
51+ current .next = list2
52+ list2 = list2 .next
53+ current = current .next
54+
55+ if list1 is not None :
56+ current .next = list1
57+ elif list2 is not None :
58+ current .next = list2
59+
60+ return temp .next
61+
62+ '''
63+ B. Recursive Approach
64+ - use recursion to merge the two lists.
65+ '''
66+ def mergeTwoListsRecursive (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
67+ if list1 is None :
68+ return list2
69+ elif list2 is None :
70+ return list1
71+
72+ if list1 .val < list2 .val :
73+ list1 .next = self .mergeTwoLists (list1 .next , list2 )
74+ return list1
75+ else :
76+ list2 .next = self .mergeTwoLists (list1 , list2 .next )
77+ return list2
You can’t perform that action at this time.
0 commit comments