Merge Two Sorted Lists (LeetCode 21)
Two singly linked lists, list1 and list2, are each sorted from the smallest value to the largest. Equal values are allowed.
Join them into one list that is also sorted. Reuse the nodes that already exist: do not create new nodes to hold the values.
Return the head of the joined list. If both lists are empty, the answer is an empty list.
Worked Examples
list1 = [1,2,4], list2 = [1,3,4][1,1,2,3,4,4]list1 = [], list2 = [][]list1 = [], list2 = [0][0]⚖️Formal Constraints & Bounds
The number of nodes in both lists is in the range
[0, 50].-100 <= Node.val <= 100list1andlist2are each sorted in non-decreasing order.
Core Insight
Both lists are sorted, so the smaller of the two front nodes is the smallest unread node of both lists: attach it and move only its pointer. Each node is attached once, in sorted order. When one list is empty, the other list is already sorted and linked, so one assignment attaches all of it.
Real-World Scenario & Production Applications
The merge step of merge sort, combining two sorted log files into one in time order, and the merge join that a database uses on two inputs already sorted by the join key.
Subproblems & Recurrence Decomposition3 Phases
Keep one pointer per list. The smaller head is the smallest unread node of both lists, so attach it to tail and move only the pointer of the list it came from.
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.nextStep-by-Step Execution Trace Table
| Step | list1.val | list2.val | Branch | Node attached to tail | Merged list so far |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 <= 1: take from list1 | 1 (list1) | 1 |
| 2 | 2 | 1 | 2 <= 1 is False: take from list2 | 1 (list2) | 1, 1 |
| 3 | 2 | 3 | 2 <= 3: take from list1 | 2 (list1) | 1, 1, 2 |
| 4 | 4 | 3 | 4 <= 3 is False: take from list2 | 3 (list2) | 1, 1, 2, 3 |
| 5 | 4 | 4 | 4 <= 4: take from list1; list1 is now empty | 4 (list1) | 1, 1, 2, 3, 4 |
| 6 | (empty) | 4 | Loop ends. tail.next = list2 attaches the rest | 4 (list2) | 1, 1, 2, 3, 4, 4 |
| 7 | return dummy.next | 1, 1, 2, 3, 4, 4 |
| 1 | dummy = ListNode(0) |
| 2 | tail = dummy |
| 3 | while list1 and list2: |
| 4 | if list1.val <= list2.val: |
| 5 | tail.next = list1 |
| 6 | list1 = list1.next |
| 7 | else: |
| 8 | tail.next = list2 |
| 9 | list2 = list2.next |
| 10 | tail = tail.next |
| 11 | tail.next = list1 if list1 else list2 |
| 12 | return dummy.next |
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Two pointers here walk two different sequences at once, not one: each sorted list has its own pointer. Both lists are sorted, so the first unread node of each list is the smallest one that list still has. The smaller of the two is therefore the smallest unread node of both lists, and it is the next node of the answer.
🗂️ The Analogy: Two Sorted Piles of Index Cards
Imagine two piles of index cards, each sorted with the smallest card on top. To build one sorted pile, look at the top card of each pile, move the smaller one to the new pile, and look again. When one pile is empty, the other pile is already sorted, so you place the whole pile on the new one in a single move.
🔑 The Key Idea in the Code
The loop stops as soon as either list is empty, so one more line must attach the list that is not empty. Leave it out and every node after the last comparison is lost.
No attach after the loop:
while list1 and list2stops as soon as either list is empty, sotail.next = list1 if list1 else list2must still attach the other list. Without it LeetCode's first example returns[1,1,2,3,4]instead of[1,1,2,3,4,4]: the last4oflist2is never attached.Looping while either list has a node:
while list1 or list2readslist1.valon an empty list and raises an error. Loop while both have a node, then attach the rest.Forgetting to move
tail: withouttail = tail.next, every attach overwritesdummy.next, so only the node from the last assignment survives, together with the nodes that follow it in its own list.Returning
dummy: the fake first node holds the extra value 0; returndummy.next.Writing into an input while merging: when the merged result goes into one of the inputs, as in Merge Sorted Array (LC 88), fill it from the back (
m + n - 1down) with the larger head, so no unread value is overwritten.
4-Phase Thought Process Model
Pattern Recognition Signals
The 10-second spot
The statement gives two lists that are each sorted ("sorted in non-decreasing order") and asks for one sorted list made from both. Two sorted sequences read together in one pass is the merge walk: one pointer per list, always attaching the smaller head, needs no sort and no extra copy.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: the list from dummy.next to tail is sorted, and no unread node (from list1 or list2 on) is smaller than any node in it. The smaller head is the smallest unread node of both lists, so attaching it keeps the invariant, and only its own pointer moves.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
This problem's traps are in Common Pitfalls above.
The 60-Second Interview Pitch
Say this out loud before you type a single line
"I'll use Merge Two Sorted. Both lists are sorted, so I keep one pointer in each list, list1 and list2, and a tail that marks the end of the merged list, starting at a dummy node. At each step I compare the two heads and attach the smaller one to the tail. I move only the pointer of the list it came from, so each node is attached once, in sorted order. If the values are equal I take list1 first, so equal values keep their input order. The loop stops as soon as one list is empty. The trap is that the other list still has nodes, so I attach it with one assignment, tail.next equals list1 if list1 else list2. Then I return dummy.next, not dummy. Every node is visited once, so it is O(M + N) time, and I only relink existing nodes, so it is
O(1)extra space."
Complexity & Mathematical Proof
O(M + N)
Look at the code: every pass of while list1 and list2 does one comparison, attaches one node to tail, and moves list1 or list2 one node forward. No pointer ever moves back, so the loop runs at most M + N times, each pass constant work. The line tail.next = list1 if list1 else list2 is one assignment, whatever the length of the list it attaches.
O(1) extra
Look at the allocations: the code creates one node, dummy, and keeps the pointers list1, list2 and tail. Every other node of the result is a node of the input, relinked with tail.next = ..., so no list is copied and there is no recursion.
T(M, N) = (passes that move list1) + (passes that move list2) <= M + N = O(M + N)
Derivation Progression
while list1 and list2: 1 comparison + 1 attach per pass
Each pass moves list1 or list2 forward by one node, so it runs at most M + N times before one list is empty.
tail.next = list1 if list1 else list2: 1 assignment
The remaining nodes are already linked, so one assignment attaches all of them, however many there are.
M + N passes x O(1) + O(1) = O(M + N)
The pointers only move forward and each node is attached once; nothing is nested.
Variable Definitions
The number of nodes in list1
The number of nodes in list2
Memory Architecture & Bounds
O(1): no recursion
O(1): the one node dummy and the pointers list1, list2 and tail
O(1) extra: the result is made of the input nodes, relinked
Boundary Best / Worst Cases
: when every node of the shorter list is smaller than every node of the longer list, the loop ends once the shorter list is attached, and the rest is one assignment
: the two lists interleave, so the loop runs until the last node of one list is attached
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
At scale the signal is two sorted inputs read together: joining two sorted tables or logs on a key, or merging sorted runs, where one cursor per input replaces an index or a hash table.
in the problem, but the same walk reads inputs of any length once: steps and no extra copy of the data, because each node is relinked, not copied. Both lists are read front to back exactly once, so they can arrive as two sorted streams. A comparison on val needs both inputs sorted in the same order; a list sorted descending, or one out-of-order node, breaks the invariant without any error.
At scale: with two sorted streams, the attach of the other list means reading that stream to its end, not stopping when the shorter one closes. A tie must take the same side every time (<= takes list1), or equal keys swap order between runs and the merge is no longer stable.
Merge Two Sorted Lists (LeetCode 21)
Two singly linked lists, list1 and list2, are each sorted from the smallest value to the largest. Equal values are allowed.
Join them into one list that is also sorted. Reuse the nodes that already exist: do not create new nodes to hold the values.
Return the head of the joined list. If both lists are empty, the answer is an empty list.
Worked Examples
list1 = [1,2,4], list2 = [1,3,4][1,1,2,3,4,4]list1 = [], list2 = [][]list1 = [], list2 = [0][0]⚖️Formal Constraints & Bounds
The number of nodes in both lists is in the range
[0, 50].-100 <= Node.val <= 100list1andlist2are each sorted in non-decreasing order.
Core Insight
Both lists are sorted, so the smaller of the two front nodes is the smallest unread node of both lists: attach it and move only its pointer. Each node is attached once, in sorted order. When one list is empty, the other list is already sorted and linked, so one assignment attaches all of it.
Real-World Scenario & Production Applications
The merge step of merge sort, combining two sorted log files into one in time order, and the merge join that a database uses on two inputs already sorted by the join key.
Subproblems & Recurrence Decomposition3 Phases
Keep one pointer per list. The smaller head is the smallest unread node of both lists, so attach it to tail and move only the pointer of the list it came from.
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.nextStep-by-Step Execution Trace Table
| Step | list1.val | list2.val | Branch | Node attached to tail | Merged list so far |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 <= 1: take from list1 | 1 (list1) | 1 |
| 2 | 2 | 1 | 2 <= 1 is False: take from list2 | 1 (list2) | 1, 1 |
| 3 | 2 | 3 | 2 <= 3: take from list1 | 2 (list1) | 1, 1, 2 |
| 4 | 4 | 3 | 4 <= 3 is False: take from list2 | 3 (list2) | 1, 1, 2, 3 |
| 5 | 4 | 4 | 4 <= 4: take from list1; list1 is now empty | 4 (list1) | 1, 1, 2, 3, 4 |
| 6 | (empty) | 4 | Loop ends. tail.next = list2 attaches the rest | 4 (list2) | 1, 1, 2, 3, 4, 4 |
| 7 | return dummy.next | 1, 1, 2, 3, 4, 4 |
| 1 | dummy = ListNode(0) |
| 2 | tail = dummy |
| 3 | while list1 and list2: |
| 4 | if list1.val <= list2.val: |
| 5 | tail.next = list1 |
| 6 | list1 = list1.next |
| 7 | else: |
| 8 | tail.next = list2 |
| 9 | list2 = list2.next |
| 10 | tail = tail.next |
| 11 | tail.next = list1 if list1 else list2 |
| 12 | return dummy.next |
Conceptual Narrative
🧭 Conceptual Foundation & Pattern Intuition
Two pointers here walk two different sequences at once, not one: each sorted list has its own pointer. Both lists are sorted, so the first unread node of each list is the smallest one that list still has. The smaller of the two is therefore the smallest unread node of both lists, and it is the next node of the answer.
🗂️ The Analogy: Two Sorted Piles of Index Cards
Imagine two piles of index cards, each sorted with the smallest card on top. To build one sorted pile, look at the top card of each pile, move the smaller one to the new pile, and look again. When one pile is empty, the other pile is already sorted, so you place the whole pile on the new one in a single move.
🔑 The Key Idea in the Code
The loop stops as soon as either list is empty, so one more line must attach the list that is not empty. Leave it out and every node after the last comparison is lost.
No attach after the loop:
while list1 and list2stops as soon as either list is empty, sotail.next = list1 if list1 else list2must still attach the other list. Without it LeetCode's first example returns[1,1,2,3,4]instead of[1,1,2,3,4,4]: the last4oflist2is never attached.Looping while either list has a node:
while list1 or list2readslist1.valon an empty list and raises an error. Loop while both have a node, then attach the rest.Forgetting to move
tail: withouttail = tail.next, every attach overwritesdummy.next, so only the node from the last assignment survives, together with the nodes that follow it in its own list.Returning
dummy: the fake first node holds the extra value 0; returndummy.next.Writing into an input while merging: when the merged result goes into one of the inputs, as in Merge Sorted Array (LC 88), fill it from the back (
m + n - 1down) with the larger head, so no unread value is overwritten.
4-Phase Thought Process Model
Pattern Recognition Signals
The 10-second spot
The statement gives two lists that are each sorted ("sorted in non-decreasing order") and asks for one sorted list made from both. Two sorted sequences read together in one pass is the merge walk: one pointer per list, always attaching the smaller head, needs no sort and no extra copy.
Formulating the Predicate & Invariants
Turning intuition into a boolean rule
Invariant: the list from dummy.next to tail is sorted, and no unread node (from list1 or list2 on) is smaller than any node in it. The smaller head is the smallest unread node of both lists, so attaching it keeps the invariant, and only its own pointer moves.
Silent Failure Traps & Edge Cases
Where confident candidates still lose points
This problem's traps are in Common Pitfalls above.
The 60-Second Interview Pitch
Say this out loud before you type a single line
"I'll use Merge Two Sorted. Both lists are sorted, so I keep one pointer in each list, list1 and list2, and a tail that marks the end of the merged list, starting at a dummy node. At each step I compare the two heads and attach the smaller one to the tail. I move only the pointer of the list it came from, so each node is attached once, in sorted order. If the values are equal I take list1 first, so equal values keep their input order. The loop stops as soon as one list is empty. The trap is that the other list still has nodes, so I attach it with one assignment, tail.next equals list1 if list1 else list2. Then I return dummy.next, not dummy. Every node is visited once, so it is O(M + N) time, and I only relink existing nodes, so it is
O(1)extra space."
Complexity & Mathematical Proof
O(M + N)
Look at the code: every pass of while list1 and list2 does one comparison, attaches one node to tail, and moves list1 or list2 one node forward. No pointer ever moves back, so the loop runs at most M + N times, each pass constant work. The line tail.next = list1 if list1 else list2 is one assignment, whatever the length of the list it attaches.
O(1) extra
Look at the allocations: the code creates one node, dummy, and keeps the pointers list1, list2 and tail. Every other node of the result is a node of the input, relinked with tail.next = ..., so no list is copied and there is no recursion.
T(M, N) = (passes that move list1) + (passes that move list2) <= M + N = O(M + N)
Derivation Progression
while list1 and list2: 1 comparison + 1 attach per pass
Each pass moves list1 or list2 forward by one node, so it runs at most M + N times before one list is empty.
tail.next = list1 if list1 else list2: 1 assignment
The remaining nodes are already linked, so one assignment attaches all of them, however many there are.
M + N passes x O(1) + O(1) = O(M + N)
The pointers only move forward and each node is attached once; nothing is nested.
Variable Definitions
The number of nodes in list1
The number of nodes in list2
Memory Architecture & Bounds
O(1): no recursion
O(1): the one node dummy and the pointers list1, list2 and tail
O(1) extra: the result is made of the input nodes, relinked
Boundary Best / Worst Cases
: when every node of the shorter list is smaller than every node of the longer list, the loop ends once the shorter list is attached, and the rest is one assignment
: the two lists interleave, so the loop runs until the last node of one list is attached
Pointer Invariant Transition Progression
Senior SWE Deconstruction & Hardware Caveats
At scale the signal is two sorted inputs read together: joining two sorted tables or logs on a key, or merging sorted runs, where one cursor per input replaces an index or a hash table.
in the problem, but the same walk reads inputs of any length once: steps and no extra copy of the data, because each node is relinked, not copied. Both lists are read front to back exactly once, so they can arrive as two sorted streams. A comparison on val needs both inputs sorted in the same order; a list sorted descending, or one out-of-order node, breaks the invariant without any error.
At scale: with two sorted streams, the attach of the other list means reading that stream to its end, not stopping when the shorter one closes. A tie must take the same side every time (<= takes list1), or equal keys swap order between runs and the merge is no longer stable.