Skip to content

K-Way Merge

Lesson 2 of 4 · 6 min

K-Way Merge

Step 1 of 17

Three lanes, each already sorted. Only the value at the front of a lane can be the next smallest overall.

The Idea

Only the front value of a sorted list can be the next smallest overall. So hold just those k heads in a min-heap.

Pop the winner, append it to the output, and push the value that stepped up behind it. The heap never grows past k, no matter how long the lists are.

Real-World Example

A postal sorting hall with k conveyor belts, each already in date order. A clerk only ever looks at the k parcels at the belt fronts, takes the oldest, and the belt behind it rolls one step forward.

The Code

Your turn

What does this print?

import heapq
heap = [(1, 0, 0), (2, 1, 0), (3, 2, 0)]   # the three heads
lists = [[1, 6], [2, 4], [3, 8]]
value, i, j = heapq.heappop(heap)
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
print(value, heap[0][0])

Mini quiz

1 / 3

How many entries does the heap hold at any moment?