Coding Problems
Merge Two Sorted Lists | Leetcode 21
Welcome to our deep dive on Merge Two Sorted Lists (Leetcode 21). This is the absolute paramount introductory linked list problem, teaching the essential Dummy Node pattern.
Problem Statement
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example:
list1 = [1,2,4], list2 = [1,3,4] => Output: [1,1,2,3,4,4]
Approach: Two Pointers + Dummy Node O(N + M)
Because both input lists are entirely guaranteed to already be sorted, we can safely just compare their respective head nodes. Whichever is smaller becomes the next node in our merged list!
- Create a
dummynode. This effortlessly anchors the very start of our new list so we don't have to write edge cases for null heads. - Maintain a
currpointer starting atdummy. - Loop while both
list1andlist2are not null.- If
list1.val <= list2.val, pointcurr.nexttolist1, and advancelist1. - Else, point
curr.nexttolist2, and advancelist2. - Always advance
currforward!
- If
- Once the loop ends, one of the lists might still have leftover nodes. Because they are already sorted, we can just attach the entire remainder of that list directly to
curr.next!
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
curr = dummy
while list1 and list2:
if list1.val <= list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next
curr = curr.next
# Attach any remaining elements
curr.next = list1 if list1 else list2
return dummy.next
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time | O(N + M) | We iterate at most N + M times across both discrete input linked lists. |
| Space | O(1) | We purely rewire preexisting pointers. We never dynamically allocate new nodes for the content itself. |