Top-k from a Stream with a Heap

easy
Unit 1 · Binary Search & Heaps0/3 to milestone

You're reading millions of scored items, such as search results or log events, and need the k largest. Sorting everything is O(nlog⁡n)O(n \log n) and needs all the data in memory. A size-k min-heap does it in O(nlog⁡k)O(n \log k) in one pass.

Implement top_k(stream, k, key=lambda x: x):

  • stream is any iterable (possibly a generator you can only read once).
  • Return the k items with the largest key, sorted from largest to smallest. If several items tie, the one that appeared earlier comes first.
  • Return all items, sorted, if there are fewer than k. Return [] for k <= 0.

Don't sort the whole stream or call heapq.nlargest. Write the heap logic yourself with heapq.heappush and heapq.heappushpop.

#heaps#streaming2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Top-k from a Stream with a Heap · TechGradify