Combine several sorted linked lists into one sorted chain containing their original nodes exactly once.
Problem
Input. A finite list of linked-list head references, each describing a nondecreasing integer chain or an empty chain.
Output. Return the head of one nondecreasing chain containing every node from every input list.
Rules. Reuse the original nodes and rewrite their links rather than copying values into replacement nodes.
Input chains must be acyclic and pairwise node-disjoint. Equal values remain separate occurrences.
Leave the head array unchanged. Empty sources contribute nothing; no nodes returns None.
Example. Chains 1 -> 4, 1 -> 3, and 2 -> 6 merge into 1 -> 1 -> 2 -> 3 -> 4 -> 6.
Both nodes valued 1 must remain in the result.
Picture
For A:1->4, B:1->3, keep candidates (1,0,A) and (1,1,B).
Emit A’s 1, then replace only A’s candidate with 4.
B’s 1 is now smallest.
Problem trace
Emitting one frontier advances only the list that supplied it
candidate min-heap
- (1,0,A1)
- (1,1,B1)
- (2,2,C2)
- input lists
- A:1->4->5; B:1->3->4; C:2->6
- heap array
- [(1,0,A1),(1,1,B1),(2,2,C2)]
- tail
- dummy
candidate min-heap
- (1,1,B1)
- (2,2,C2)
- (4,0,A4)
- popped
- not shown→(1,0,A1)
- pushed
- not shown→(4,0,A4)
- tail
- dummy→A1
candidate min-heap
- (2,2,C2)
- (4,0,A4)
- (3,1,B3)
- popped
- (1,0,A1)→(1,1,B1)
- pushed
- (4,0,A4)→(3,1,B3)
- tail
- A1→B1
candidate min-heap
- (3,1,B3)
- (4,0,A4)
- (6,2,C6)
- popped
- (1,1,B1)→(2,2,C2)
- pushed
- (3,1,B3)→(6,2,C6)
- tail
- B1→C2
candidate min-heap
- (4,0,A4)
- (6,2,C6)
- (4,1,B4)
- popped
- (2,2,C2)→(3,1,B3)
- pushed
- (6,2,C6)→(4,1,B4)
- tail
- C2→B3
candidate min-heap
- (4,1,B4)
- (6,2,C6)
- (5,0,A5)
- popped
- (3,1,B3)→(4,0,A4)
- pushed
- (4,1,B4)→(5,0,A5)
- tail
- B3→A4
candidate min-heap
- (5,0,A5)
- (6,2,C6)
- popped
- (4,0,A4)→(4,1,B4)
- pushed
- (5,0,A5)→none: node.next is null
- tail
- A4→B4
candidate min-heap
- (6,2,C6)
- popped
- (4,1,B4)→(5,0,A5)
- tail
- B4→A5
- output order
- [A1,B1,C2,B3,A4,B4]→[A1,B1,C2,B3,A4,B4,A5]
- heap state
- not shown→[]
- popped
- (5,0,A5)→(6,2,C6)
- values
- not shown→1,1,2,3,4,4,5,6
- node order
- not shown→A1->B1->C2->B3->A4->B4->A5->C6
- result
- not shown→1->1->2->3->4->4->5->6
- popped
- (6,2,C6)→not shown
- Recognize it
- Use it when k individually sorted streams must be merged and only their current heads can be candidates for the next global minimum.
- Keep true
- The heap contains exactly the first unmerged node of each nonexhausted list, and the tail follows all nodes already popped in nondecreasing tuple order.
- Reuse it
- For sorted sources, keep only one frontier item per source and replace it from the same source after extraction. The pattern transfers to external merge, log aggregation, and k-way iterators.
Reference drawing
Problem trace
Emitting one frontier advances only the list that supplied it
Execution trace
candidate min-heap
- (1,0,A1)
- (1,1,B1)
- (2,2,C2)
- input lists
- A:1->4->5; B:1->3->4; C:2->6
- heap array
- [(1,0,A1),(1,1,B1),(2,2,C2)]
- tail
- dummy
candidate min-heap
- (1,1,B1)
- (2,2,C2)
- (4,0,A4)
- popped
- not shown→(1,0,A1)
- pushed
- not shown→(4,0,A4)
- tail
- dummy→A1
candidate min-heap
- (2,2,C2)
- (4,0,A4)
- (3,1,B3)
- popped
- (1,0,A1)→(1,1,B1)
- pushed
- (4,0,A4)→(3,1,B3)
- tail
- A1→B1
candidate min-heap
- (3,1,B3)
- (4,0,A4)
- (6,2,C6)
- popped
- (1,1,B1)→(2,2,C2)
- pushed
- (3,1,B3)→(6,2,C6)
- tail
- B1→C2
candidate min-heap
- (4,0,A4)
- (6,2,C6)
- (4,1,B4)
- popped
- (2,2,C2)→(3,1,B3)
- pushed
- (6,2,C6)→(4,1,B4)
- tail
- C2→B3
candidate min-heap
- (4,1,B4)
- (6,2,C6)
- (5,0,A5)
- popped
- (3,1,B3)→(4,0,A4)
- pushed
- (4,1,B4)→(5,0,A5)
- tail
- B3→A4
candidate min-heap
- (5,0,A5)
- (6,2,C6)
- popped
- (4,0,A4)→(4,1,B4)
- pushed
- (5,0,A5)→none: node.next is null
- tail
- A4→B4
candidate min-heap
- (6,2,C6)
- popped
- (4,1,B4)→(5,0,A5)
- tail
- B4→A5
- output order
- [A1,B1,C2,B3,A4,B4]→[A1,B1,C2,B3,A4,B4,A5]
- heap state
- not shown→[]
- popped
- (5,0,A5)→(6,2,C6)
- values
- not shown→1,1,2,3,4,4,5,6
- node order
- not shown→A1->B1->C2->B3->A4->B4->A5->C6
- result
- not shown→1->1->2->3->4->4->5->6
- popped
- (6,2,C6)→not shown
- Recognize it
- Use it when k individually sorted streams must be merged and only their current heads can be candidates for the next global minimum.
- Keep true
- The heap contains exactly the first unmerged node of each nonexhausted list, and the tail follows all nodes already popped in nondecreasing tuple order.
- Reuse it
- For sorted sources, keep only one frontier item per source and replace it from the same source after extraction. The pattern transfers to external merge, log aggregation, and k-way iterators.
Every hidden source node is at least its exposed head. The heap minimum is therefore globally safe. The source index resolves equal values without comparing node objects.
Code
This local definition supplies the platform node type before the unchanged reference.
class ListNode:
def __init__(self, val: int = 0, next_node: "ListNode | None" = None):
self.val = val
self.next = next_node
import heapq
def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None:
heap: list[tuple[int, int, ListNode]] = []
for index, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, index, node))
dummy = ListNode(0)
tail = dummy
while heap:
_, index, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, index, node.next))
return dummy.next
Cost: scalar operations and heap space for k sources and n nodes.
The reference allocates only one dummy node.
The platform supplies ListNode with val and next; this snippet assumes that definition.
Change the Requirement
Preserve All Input Links
New task: Return independent output nodes.
Picture and change: Copy the emitted value instead of reusing its node.
Code: Use heapq and ListNode above.
def merge_k_lists_copy(lists: list[ListNode | None]) -> ListNode | None:
heap = [(node.val, index, node) for index, node in enumerate(lists) if node]
heapq.heapify(heap)
dummy = tail = ListNode()
while heap:
value, index, node = heapq.heappop(heap)
tail.next = ListNode(value)
tail = tail.next
if node.next:
heapq.heappush(heap, (node.next.val, index, node.next))
return dummy.next
Check: A:1->4, B:1->3 yield fresh 1->1->3->4 nodes; both inputs retain their links.
Use when: Output ownership must be independent; allocation adds .
Consume Sorted Iterables
New task: Merge values without linked nodes.
Picture and change: Each heap entry owns one iterator and its current value.
Code: The collection of sources must be finite.
def merge_sorted_iterables(sources):
heap = []
for index, source in enumerate(sources):
iterator = iter(source)
try:
value = next(iterator)
except StopIteration:
continue
heapq.heappush(heap, (value, index, iterator))
while heap:
value, index, iterator = heapq.heappop(heap)
yield value
try:
following = next(iterator)
except StopIteration:
continue
heapq.heappush(heap, (following, index, iterator))
Check: list(merge_sorted_iterables([[1,4],[1,3],[]])) returns [1,1,3,4].
Use when: Sources advance lazily; heap state remains .
Reconstruct
Why require disjoint nodes for the relinking reference?
Reasoned answer
If two heads reference the same node, that object can enter the heap twice.
Appending it twice may set its next pointer to itself, creating a cycle.
Equal values are safe; repeated identities are not.
The copy variant avoids output-link mutation but still assumes finite acyclic source traversals.
Infinite value streams need a separate liveness contract. An infinite sequence of equal values from one source can indefinitely postpone equal values from another source. Sorted output does not imply fairness among sources.