Combine two sorted linked lists into one sorted chain while reusing all their original nodes.
Problem
Input. Two heads of nondecreasing linked lists with comparable values; either head may be None.
Output. Return the head of a nondecreasing chain containing every node from both lists exactly once.
Rules. The input chains must be acyclic and node-disjoint, with permission to rewrite their links.
Reuse the original nodes rather than creating replacement output nodes.
Retain equal-valued occurrences. Two empty inputs return None; one empty input leaves the other chain as the result.
Example. A: 1 -> 4 -> 7 and B: 2 -> 3 -> 8 produce 1 -> 2 -> 3 -> 4 -> 7 -> 8.
The nodes valued 1 and 2 are still the original A and B nodes, not copies.
Picture
Keep two unconsumed heads, first and second, plus the last selected node, tail.
A dummy node provides one uniform attachment point, including the first result.
Any later value in either sorted suffix is at least its head value.
Therefore, the smaller head is globally next.
On equality, choose first, preserving input order and first-source priority among equal values.
Select A1, B2, B3, A4, then A7.
Only the chosen source advances at each decision.
Now first is empty; attach the remaining B8 suffix with one assignment.
No more comparisons are needed.
The path through tail is the selected prefix.
Its old outgoing link may still reach an unselected node until the next attachment overwrites it.
The picture separates the selected prefix from unconsumed sources; omitted old links are not assertions of None.
Problem trace
Suffix identity contrast: attach the surviving chain with one splice
Reference drawing
Problem trace
Attach the remaining suffix directly once the other list is exhausted
Execution trace
- edges
- [A1 -> A4, A4 -> A7, B2 -> B3, B3 -> B8]
- input
- A:1->4->7; B:2->3->8
- fixed prefix
- empty
- edges
- [A1 -> A4, A4 -> A7, B2 -> B3, B3 -> B8]→[dummy -> A1, A4 -> A7, B2 -> B3, B3 -> B8]
- fixed prefix
- empty→1
- comparison
- not shown→1 <= 2
- edges
- [dummy -> A1, A4 -> A7, B2 -> B3, B3 -> B8]→[dummy -> A1, A1 -> B2, A4 -> A7, B3 -> B8]
- fixed prefix
- 1→1->2
- comparison
- 1 <= 2→4 > 2
- edges
- [dummy -> A1, A1 -> B2, A4 -> A7, B3 -> B8]→[dummy -> A1, A1 -> B2, B2 -> B3, A4 -> A7]
- fixed prefix
- 1->2→1->2->3
- comparison
- 4 > 2→4 > 3
- edges
- [dummy -> A1, A1 -> B2, B2 -> B3, A4 -> A7]→[dummy -> A1, A1 -> B2, B2 -> B3, B3 -> A4]
- fixed prefix
- 1->2->3→1->2->3->4
- comparison
- 4 > 3→4 <= 8
- edges
- [dummy -> A1, A1 -> B2, B2 -> B3, B3 -> A4]→[dummy -> A1, A1 -> B2, B2 -> B3, B3 -> A4, A4 -> A7]
- fixed prefix
- 1->2->3->4→1->2->3->4->7
- comparison
- 4 <= 8→7 <= 8
- edges
- [dummy -> A1, A1 -> B2, B2 -> B3, B3 -> A4, A4 -> A7]→[dummy -> A1, A1 -> B2, B2 -> B3, B3 -> A4, A4 -> A7, A7 -> B8]
- fixed prefix
- 1->2->3->4->7→1->2->3->4->7->8
- result
- not shown→[1,2,3,4,7,8]
- Recognize it
- Two sorted node streams must be merged by relinking existing nodes.
- Keep true
- The path from dummy through tail is the consumed sorted prefix; first and second begin untouched suffixes. The old link after tail may remain until the next attachment overwrites it.
- Reuse it
- Emit the smaller frontier and advance only its source; append the remaining sorted suffix in constant time.
Code
The platform supplies ListNode; this definition makes the published blocks runnable together locally.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(first: ListNode | None, second: ListNode | None) -> ListNode | None:
dummy = ListNode(0)
tail = dummy
while first and second:
if first.val <= second.val:
tail.next, first = first, first.next
else:
tail.next, second = second, second.next
tail = tail.next
tail.next = first or second
return dummy.next
The tuple assignment evaluates the source successor before assigning either target. Later iterations can therefore overwrite output links without losing the unconsumed suffix. The result contains all original data nodes; the dummy is excluded.
Whole-function work is under constant-cost comparisons, with extra storage.
Attaching the final suffix does not advance tail or the remaining source cursor.
Failure Check
Passing the same single node as both inputs makes the reference link that node to itself. Disjointness is a real precondition, not a harmless simplification.
Change to Independent Output Nodes
New task: Preserve every original next link.
Picture and change: Allocate one new node per selected value, including every value in the final suffix.
def merge_two_copy(first, second):
dummy = tail = ListNode(0)
while first or second:
if first is not None and (second is None or first.val <= second.val):
value, first = first.val, first.next
else:
value, second = second.val, second.next
tail.next = ListNode(value)
tail = tail.next
return dummy.next
Check: The example keeps the same value order while sharing no output nodes with either input. All original links stay unchanged. Time remains ; allocation becomes nodes. Values themselves are assigned, not recursively copied.
Use when: Input ownership prohibits rewiring.
Change to Descending Inputs
New task: Merge two nonincreasing chains into one nonincreasing chain.
Picture and change: Choose the larger frontier with >=, retaining the same cursor and tail updates.
def merge_descending(first, second):
dummy = tail = ListNode(0)
while first and second:
if first.val >= second.val:
tail.next, first = first, first.next
else:
tail.next, second = second, second.next
tail = tail.next
tail.next = first or second
return dummy.next
Check: [7,4,1] and [8,3,2] become [8,7,4,3,2,1], reusing their six nodes.
Equal values still prefer the first source.
Reversing only the comparator on ascending inputs does not satisfy this contract.
Use when: Both the source order and required output order change.
Transfer Check
Why does merging many sorted sources often use a heap?
Answer
The same frontier proof applies, but choosing the smallest among many heads needs more than one binary comparison. A heap orders those available heads efficiently.