Learn / Heaps and priority queues
K-way merge
To merge k sorted lists, put the front of each list into a min heap. Pop the smallest, output it, and push the next item from the same list. The heap never holds more than k items, so merging N items costs O(N log k).
How to recognise it
- Several sorted lists, arrays or rows must be combined or searched together.
- You need the smallest item across k sources, again and again.
- A matrix whose rows are sorted, treated as k sorted lists.
The picture
The heap holds one candidate per list: its current front. The smallest of all fronts is the smallest item left overall, because each list is sorted.
heap = [(list[i][0], i, 0) for each non-empty list i]
while heap:
(value, i, j) = pop
output value
if j + 1 < len(list[i]): push (list[i][j + 1], i, j + 1)
Variants
- Linked lists: push nodes instead of indexes; the node's
nextis its list's next item. - Smallest range: keep one value from every list and track the largest of them. The range
[heap top, max]covers every list. Pop the top, push its successor, update the max, and repeat until a list runs out. - Sorted matrix: each row is a sorted list.
Merging pairs of lists one after another costs O(N × k); the heap brings it to O(N log k). Merging in pairs like merge sort, in a tree of rounds, also gives O(N log k).
Common mistakes
- Pushing every item at the start, which is just sorting: O(N log N).
- In Python, putting nodes in tuples with equal values: add the list index as a tie-breaker so nodes are never compared.
Problems
- Merge “K” sorted arraysmediumguide ready
- Merge k Sorted Listshardguide ready
- Smallest range in “K” Listshardguide ready