Merge k sorted linked lists into one. The next node is always one of the k heads, so keep them in a min-heap and pop the smallest.
▼The problem
LeetCode 23 (Hard). Given an array of k linked lists, each sorted in ascending order, merge them into one sorted linked list and return its head.
Example: lists = [[1,4,5],[1,3,4],[2,6]] → [1,1,2,3,4,4,5,6].
import heapq
def merge_k_lists(lists):
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = tail = ListNode()
while heap:
val, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.nextTRY IT ON LEETCODE ▶The solution
import heapq
def merge_k_lists(lists):
heap = []
for i, node in enumerate(lists):
if node:
heapq.heappush(heap, (node.val, i, node))
dummy = tail = ListNode()
while heap:
val, i, node = heapq.heappop(heap)
tail.next = node
tail = node
if node.next:
heapq.heappush(heap, (node.next.val, i, node.next))
return dummy.nextTranscript
Merge k Sorted Lists. You're given k linked lists, each one already sorted. Merge them all into one sorted list, and return its head.
Take three lists. One, four, five. One, three, four. And two, six. That's eight nodes. Merged, they read: one, one, two, three, four, four, five, six.
The simple way merges them one at a time: the first two, then that result with the third. But the growing result gets walked again on every merge. With N nodes in all, that's order k times N. Dumping every value and sorting costs N log N, and ignores that each list is already sorted.
Here's the key. The next node of the answer is always one of the k heads, since nothing behind a head can be smaller. So keep just the heads in a min-heap, smallest at the spout. Pop the smallest, append it, and push the next node from its list. The heap never holds more than k nodes.
Let's run it. The heads go in: one, one, two. Pop one from list zero, push its four. Pop one from list one, push three. Pop two, push six. Pop three, push four. Now the fours tie, and the lower list index wins, so list zero's four goes first and pushes five. Then four, five and six drain out. The heap is empty, and the list is sorted.
In code, push each head as a tuple: value, list index, node. On a tie, the index decides, so two nodes are never compared. A dummy node starts the answer. While the heap has nodes, pop one, link it on, and push its next if there is one. Return the dummy's next.
Each of the N nodes is pushed once and popped once, at log k per heap step. So the time is order N log k, and the extra space is order k, for the heap.
Keep only the heads, and always take the smallest. That's Merge k Sorted Lists.