Merge Two Sorted Lists
Merge Two Sorted Lists is LeetCode 21 (Easy). You get the heads of two singly linked lists, list1 and list2, each sorted in non-decreasing order.
- Join them into one sorted list by splicing the existing nodes together, not by creating new ones.
- Return the head of the merged list.
- Either list, or both, may be empty.
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both list1 and list2 are sorted in non-decreasing order.
Intuition
Both lists are sorted, so the smallest node left is always one of the two current heads. Take the smaller head, attach it to the result, and repeat. This is the merge step of merge sort, done with pointers instead of array copies.
- Dummy node: start the result with a throwaway node and a
tailpointer on it. Every attach is thentail.next = node, with no special case for the first node. - Leftover in one link: when one list runs out, the other is still sorted and no smaller than
tail, so one assignment attaches all of it.
Building a linked list from front to back while choosing nodes from more than one source. A dummy head plus a tail pointer is the standard tool whenever the first node of the answer is not known in advance.
Approach
Before reading on, decide which two nodes could be the smallest in the merged list, and what you do with the rest of one list once the other is empty. Aim for O(m + n) time and no new nodes.
Two ways to solve it
Walk both lists with a tail pointer and attach the smaller head each time.
- No stack: constant extra memory, whatever the length.
- Leftover: linked in one assignment.
The safe default in an interview.
The smaller head is the answer's head; its next is the merge of everything else.
- Short: about six lines, no dummy node.
- Watch out: one call per node, so very long lists can overflow the call stack.
Fine for 50 nodes per list.
Both visit each node once. The iterative version wins because it uses constant memory, so it is the one the steps, code and demo follow; the recursive code comes after the demo.
Create a dummy node and a tail
Make dummy = ListNode() and set tail = dummy. The dummy gives tail a node to attach to before the result has any real node, so the loop body never needs an empty-result check.
Attach the smaller head
While both lists are non-empty, compare list1.val and list2.val. Set tail.next to the smaller node and advance that list. Taking list1 on a tie keeps equal values in their original order.
Move the tail forward
Set tail = tail.next after each attach, so tail is always the last node of the result and the next attach is O(1).
Attach whatever is left
When the loop ends, at most one list still has nodes. Set tail.next = list1 or list2. The leftover is already sorted and starts at a value no smaller than tail, so it can be linked as a whole.
Return the node after the dummy
Return dummy.next. The dummy was only scaffolding; if both inputs were empty, dummy.next is still None, which is the correct empty answer.
Code in Python, C++ and Java
Recursive merge
If either list is empty, the answer is the other one. Otherwise the smaller head comes first, and its next is the merge of the remaining nodes. Each call handles one node, so the call stack grows to m + n frames.
Common pitfalls
Forgetting the leftover nodes
while list1 and list2:
...
return dummy.nextwhile list1 and list2:
...
tail.next = list1 or list2
return dummy.nextWith list1 = [1, 2] and list2 = [3, 4, 5], the loop stops once 1 and 2 are attached and returns [1, 2]. The nodes 3, 4 and 5 are never linked.
Not moving the tail
tail.next = list1 list1 = list1.next
tail.next = list1 list1 = list1.next # after the if/else: tail = tail.next
With [1, 2] and [3], every attach overwrites dummy.next, and the final leftover link overwrites it once more. The answer comes back as [3] instead of [1, 2, 3].
Returning the dummy itself
return dummy
return dummy.next
With [1] and [2], this returns [0, 1, 2]: the placeholder value 0 shows up as an extra first node.
Edge cases
The loop never runs and tail.next = list1 or list2 returns the other list unchanged.
Nothing is attached, so dummy.next is None, the empty list.
Complexity
Merge Two Sorted Lists FAQ
Why is splicing O(1) space if the output has m + n nodes?
The output is made of the input nodes themselves. Only their next pointers change, so no node is allocated except the dummy. Building fresh nodes with copied values would use O(m + n).
How does this extend to k sorted lists?
Merging lists one by one into a growing result costs O(k · N) for N total nodes. Merging them in pairs, or keeping the k current heads in a min-heap, brings it down to O(N log k).