Merge Two Sorted Lists (LeetCode 21): Solution and Explanation
You are given the heads of two linked lists, each already sorted in non-decreasing order, and must combine them into one sorted list. The result should reuse the existing nodes by relinking them rather than allocating new ones.
Watch it run step by step
Try your own input and write the code →Intuition
The lazy approach is to pour every value into an array, sort it, and build a new list. That costs O((n + m) log(n + m)) time and ignores the fact that both inputs are already sorted, which is the whole hint of the problem.
Because both lists are sorted, the smallest remaining value overall must be at the head of one of them. So you only ever need to compare two nodes: the current front of each list. Take the smaller one, attach it to the output, advance in the list it came from, and repeat. This is exactly the merge step of merge sort, applied to linked lists.
The fiddly part with linked lists is the very first node, since you do not know in advance which list provides the head. A dummy node removes that special case. You always append to tail.next, and at the end the real head is simply dummy.next. When one list runs out, the other one is already sorted and can be attached in a single pointer assignment, so there is no need to loop over the leftovers.
Approach: Iterative merge with a dummy head
- Create a
dummynode and settail = dummy. The dummy'snextwill become the merged list's head. - While both
list1andlist2are non-empty, comparelist1.valwithlist2.val. - If
list1.valis smaller, linktail.nexttolist1and advancelist1. Otherwise linktail.nexttolist2and advancelist2. - Move
tailforward to the node just attached. - After the loop, at most one list still has nodes. Attach whichever is non-empty to
tail.next. - Return
dummy.next, which skips the placeholder node.
Step-by-step example
list1 = [1,2,4], list2 = [1,3,4]
- Compare 1 and 1. Since
list1.val < list2.valis false on a tie, take 1 fromlist2. Output: 1. - Compare 1 from
list1with 3. Take 1 fromlist1. Output: 1, 1. - Compare 2 with 3. Take 2 from
list1. Output: 1, 1, 2. - Compare 4 with 3. Take 3 from
list2. Output: 1, 1, 2, 3. - Compare 4 with 4. The tie goes to
list2again, so take its 4, andlist2is now empty. - Attach the rest of
list1, which is the single node 4. The result is [1,1,2,3,4,4].
Code: Python, Java, C++
1class Solution:
2 def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
3 dummy = ListNode()
4 tail = dummy
5
6 while list1 and list2:
7 if list1.val < list2.val:
8 tail.next = list1
9 list1 = list1.next
10 else:
11 tail.next = list2
12 list2 = list2.next
13 tail = tail.next
14
15 if list1:
16 tail.next = list1
17 elif list2:
18 tail.next = list2
19
20 return dummy.next1class Solution {
2 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
3 ListNode dummy = new ListNode();
4 ListNode tail = dummy;
5
6 while (list1 != null && list2 != null) {
7 if (list1.val < list2.val) {
8 tail.next = list1;
9 list1 = list1.next;
10 } else {
11 tail.next = list2;
12 list2 = list2.next;
13 }
14 tail = tail.next;
15 }
16
17 if (list1 != null) tail.next = list1;
18 else if (list2 != null) tail.next = list2;
19
20 return dummy.next;
21 }
22}1class Solution {
2public:
3 ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
4 ListNode dummy;
5 ListNode *tail = &dummy;
6
7 while (list1 && list2) {
8 if (list1->val < list2->val) {
9 tail->next = list1;
10 list1 = list1->next;
11 } else {
12 tail->next = list2;
13 list2 = list2->next;
14 }
15 tail = tail->next;
16 }
17
18 if (list1) tail->next = list1;
19 else if (list2) tail->next = list2;
20
21 return dummy.next;
22 }
23};Time and space complexity
O(n + m)
Each comparison places exactly one node into the result, so the loop runs at most n + m times, and the final splice of the leftover list is a single assignment.
O(1)
The merge only relinks existing nodes. Apart from the dummy node and a couple of pointers, nothing extra is allocated.
Other approaches
Recursive merge (time O(n + m), space O(n + m))
Return the smaller head and set its next to the merge of the remaining lists. It is short and elegant, but every node adds a stack frame, so very long lists can hit recursion limits.
Collect and sort (time O((n + m) log(n + m)), space O(n + m))
Copy all values into an array, sort it, and build a new list. It is simple but ignores the existing order and allocates new nodes.
Common mistakes
- Forgetting to advance
tailafter attaching a node, which makes every new node overwrite the previous link. - Looping over the leftover list node by node instead of attaching it directly. It works but is unnecessary since the remainder is already sorted and linked.
- Returning
dummyinstead ofdummy.next, which puts a stray 0 at the front of the result. - Not handling an empty input. If either list starts empty, the loop is skipped and the other list must still be returned through the final splice.
Frequently asked questions
Why use a dummy node when merging linked lists?
Without a dummy, you need special code to pick the head before the loop starts. The dummy gives you a fixed node to append to, so every step looks the same and the real head is just dummy.next.
Is the recursive solution better than the iterative one?
Both run in O(n + m) time. The iterative version uses O(1) extra space, while recursion uses a stack frame per node, so the iterative version is safer for long lists.
Is the merge stable when values are equal?
This code takes from list2 on ties because it uses a strict less-than comparison. If you need nodes from list1 to come first on equal values, change the comparison to <=.
How does this relate to Merge K Sorted Lists?
Merging two lists is the building block for merging k lists. You can merge the k lists in pairs, halving the count each round, or use a min-heap that always exposes the smallest current head. Both reach O(N log k) time for N total nodes.