Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get the heads of two linked lists, list1 and list2. Each list is already sorted from smallest to largest. Join them into one sorted list using the existing nodes (relink them; don't copy values into new nodes), and return the head of the result.
Either list can be empty. Each has at most 50 nodes, and values can be negative.
Example: list1 = 1 → 2 → 4, list2 = 1 → 3 → 4 → 1 → 1 → 2 → 3 → 4 → 4.
Start with brute force
Walk both lists and copy every value into an array. Sort the array. Build a fresh list from it.
It works, but it throws away the best fact you were given: both lists are already sorted. Sorting costs O((n + m) log(n + m)), and you've used O(n + m) extra memory for the array and the new nodes. You can merge in one pass with no extra memory.
Building the intuition
Imagine two queues of students, each lined up shortest to tallest, and you need one combined line, shortest to tallest.
Who goes first in the combined line? The shortest student overall. That's either the front of queue A or the front of queue B; nobody further back can be shorter than the person in front of them. So compare the two fronts, take the smaller, repeat. That's the whole algorithm.
Now the linked-list part. "Take the smaller front node and put it at the end of the result" means you need to know where the end of the result is. Keep a pointer tail to the last node you attached. Attaching is then tail.next = node; tail = node.
But on the very first step there is no last node. You'd write an if result is empty branch just for the head. That branch is where bugs live.
The fix is the dummy head: a fake node you create before the loop. tail starts on it, so there's always a node to attach to. When you're done, the real list starts at dummy.next.
The optimal approach
- Create
dummy, a throwaway node. Settail = dummy. - While both lists still have nodes:
- If
list1.val <= list2.val, attachlist1(tail.next = list1) and movelist1forward. - Otherwise attach
list2and movelist2forward. - Move
tailto the node you just attached.
- If
- One list is now empty. Attach whatever is left of the other:
tail.next = list1 or list2. - Return
dummy.next.
The subtle detail is step 3. You don't need a second loop to copy the leftovers. The remaining nodes are already linked to each other and already sorted, and every one of them is at least as big as everything you've placed. One assignment hangs the whole chain on.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode() # fake first node, so "attach to the end" never needs a special case
tail = dummy # last node of the merged list so far
while list1 and list2:
# take the smaller front node; <= keeps equal values in their original order
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
# one list is empty; the other is already sorted, so hang it on in one move
tail.next = list1 if list1 else list2
return dummy.next # skip the fake nodeclass Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummy; // fake first node, so "attach to the end" never needs a special case
ListNode* tail = &dummy; // last node of the merged list so far
while (list1 != nullptr && list2 != nullptr) {
// take the smaller front node; <= keeps equal values in their original order
if (list1->val <= list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
// one list is empty; the other is already sorted, so hang it on in one move
tail->next = (list1 != nullptr) ? list1 : list2;
return dummy.next; // skip the fake node
}
};class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(); // fake first node, so "attach to the end" never needs a special case
ListNode tail = dummy; // last node of the merged list so far
while (list1 != null && list2 != null) {
// take the smaller front node; <= keeps equal values in their original order
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
// one list is empty; the other is already sorted, so hang it on in one move
tail.next = (list1 != null) ? list1 : list2;
return dummy.next; // skip the fake node
}
}/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function (list1, list2) {
const dummy = new ListNode(); // fake first node, so "attach to the end" never needs a special case
let tail = dummy; // last node of the merged list so far
while (list1 !== null && list2 !== null) {
// take the smaller front node; <= keeps equal values in their original order
if (list1.val <= list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
// one list is empty; the other is already sorted, so hang it on in one move
tail.next = list1 !== null ? list1 : list2;
return dummy.next; // skip the fake node
};Dry run
list1 = 1 → 2 → 4, list2 = 1 → 3 → 4. "Merged so far" is the chain after dummy.
| Step | list1 front | list2 front | Take | Merged so far |
|---|---|---|---|---|
| 1 | 1 | 1 | list1's 1 (tie, <=) | 1 |
| 2 | 2 | 1 | list2's 1 | 1 → 1 |
| 3 | 2 | 3 | 2 | 1 → 1 → 2 |
| 4 | 4 | 3 | 3 | 1 → 1 → 2 → 3 |
| 5 | 4 | 4 | list1's 4 (tie) | 1 → 1 → 2 → 3 → 4 |
| end | null | 4 | attach rest of list2 | 1 → 1 → 2 → 3 → 4 → 4 |
Return dummy.next, the first 1.
Complexity
- Time: O(n + m). Each loop step places one node for good, and the leftover attach is O(1).
- Space: O(1). Just
dummyandtail. We relink existing nodes instead of creating new ones.
Edge cases and traps
- One or both lists empty. The loop never runs and step 3 returns the other list (or
null). No special case needed. - Returning
dummyinstead ofdummy.next. You'd return an extra fake node at the front with value0. - Forgetting
tail = tail.next. Every new node would overwritedummy.next, and you'd return one node. - Moving the wrong list forward. If you attach
list1, advancelist1, notlist2. Write the two branches side by side so they mirror each other. - Copying leftovers one by one. It works, but it's extra code for nothing. One assignment does it.
Say it in the interview
"Both lists are sorted, so the smallest remaining node is always at the front of one of them. I'll compare the two fronts, attach the smaller one to the end of my result, and advance that list. A dummy head node means I never special-case the first attach, and a tail pointer makes each attach O(1). When one list runs out, I attach the rest of the other in one step. That's O(n + m) time and O(1) extra space."
Follow-ups interviewers ask
- "Can you do it recursively?" Yes: the smaller head's
nextbecomes the merge of the rest. It's elegant, but it uses O(n + m) stack space. - "What about k sorted lists?" That's Merge k Sorted Lists. Put the k front nodes in a min-heap and repeatedly pop the smallest: O(N log k) for N total nodes. Or merge the lists in pairs, like merge sort.
- "Why does this matter?" It's the merge step of merge sort on linked lists, which is how you sort a linked list in O(n log n) without random access.
Practise the same idea
This is Day 44 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free