Sub topic 10
Top-k selection with a bounded heap
This chapter assumes you know Python lists and tuples, Big-O notation, and the heapq functions heappush, heappop and heapreplace. It also assumes you know that heapq is a min-heap, so heap[0] is the smallest item.
The problem
You have a stream or list of n values and want the k largest. Sorting everything costs O(n log n) time and O(n) memory. If k is much smaller than n, or the data arrives as a stream you cannot store, a heap does better.
The idea: a min-heap of size k
Keep a min-heap that never holds more than k items. It holds the k largest values seen so far. Because it is a min-heap, heap[0] is the smallest of those k values. That value is the entry bar a new item must beat.
For each new item x:
- If the heap has fewer than k items, push x.
- Otherwise, if x is larger than
heap[0], replace the root with x. The old smallest value is no longer in the top k. - Otherwise, ignore x.
A max-heap would be the wrong choice here. You need quick access to the smallest of the kept items, because that is the one you may evict.
Implementation
import heapq
def top_k(items, k):
if k <= 0:
return []
heap = []
for x in items:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x)
return sorted(heap, reverse=True)
print(top_k([7, 2, 9, 4, 11, 5], 3)) # [11, 9, 7]heapreplace pops the smallest item and pushes the new one in a single step. That is cheaper than calling heappop and then heappush. The final sorted call orders only k items, so it costs O(k log k).
Cost
Each of the n items costs one comparison with heap[0], which is O(1). Only items that enter the heap cost O(log k). In the worst case every item enters, for example when the input is in ascending order. That gives O(n log k) time. Memory is O(k), regardless of n.
| Approach | Time | Extra memory |
|---|---|---|
| Sort all, take first k | O(n log n) | O(n) |
| Bounded min-heap | O(n log k) | O(k) |
When k is close to n, the gap shrinks and plain sorting is often simpler and fast enough.
Library shortcuts
The standard library already provides this pattern:
import heapq
data = [7, 2, 9, 4, 11, 5]
print(heapq.nlargest(3, data)) # [11, 9, 7]
print(heapq.nsmallest(3, data)) # [2, 4, 5]
words = ["pear", "fig", "banana", "kiwi"]
print(heapq.nlargest(2, words, key=len)) # ['banana', 'pear']Both functions accept a key argument. Use your own loop when you need custom logic, such as stopping early or updating a result while a stream is still arriving.
Common errors
- Using a max-heap of size k. The root would be the largest kept item, which tells you nothing about what to evict.
- Comparing with
>=and replacing on equal values. This does extra work and changes which of the tied items you keep. - Forgetting
k <= 0. Withk = 0, the code would reachheap[0]on an empty list and raise anIndexError. - Pairing scores with unorderable payloads. If you store
(score, item)and two scores tie, Python compares the items next. Add a counter as a tie-breaker, as in the earlier chapter on tuple priorities.
Exercise
You process one billion numbers from a stream and need the 10 largest. Why is a min-heap of size 10 better than sorting, and what are the time and memory costs?
Show answer
Sorting needs all one billion numbers in memory and costs O(n log n). The bounded min-heap stores only 10 numbers, so memory is O(k) = O(10). Each number is compared with the root, which is O(1), and only numbers larger than the root cost an O(log 10) replacement. Total time is O(n log k).
Exercise
Why does top_k use a min-heap even though it returns the largest values?
Show answer
The item most at risk of being evicted is the smallest of the kept values. A min-heap exposes it at heap[0] in O(1) time and removes it in O(log k).