14/40
Part 4 of 8 · The k bestLearn and do

Keep the k best in a heap of size k

The first pattern. Out of n items, you want the k best: the k closest points to the origin, the k largest files, the k most recent events. There are three ways:

  • Sort everything and take k: O(n log n) time and O(n) memory.
  • Heapify a copy and pop k times: O(n + k log n) time, and O(n) memory for the copy.
  • Keep a heap of only k items, the best so far, and let each new item replace the worst of them if it beats it: O(n log k) time and O(k) memory. This one also works on a stream you can't hold.

The top of a size-k heap is the item a newcomer has to beat

Predict

A min-heap of size 3 keeps the 3 largest of the stream 5, 1, 8, 3, 9. After 9 arrives, what's on top: the value a newcomer has to beat?

Pick an answer above to see the rest