TRACK B · ALGORITHMmedium•NOVEMBER 2026•5 MIN
Min-Heap Top-K: Streaming Largest Elements in O(n log K)
Why finding the K largest items in a 10M-event stream uses a MIN-heap capped at size K.
heaptop-kstreamingpriority-queue
The core idea
To retain the K largest items without sorting all n records, keep a MIN-heap of size K. The root (heap[0]) is the weakest winner—so evicting the root whenever size hits K+1 keeps memory at O(K).
Watch it run
Step through the trace below (or turn on Predict Mode) to watch the invariant hold at every step.
LOADING MIN-HEAP TOP-K SIM...
What to say out loud
Canonical Python template
import heapq
def top_k_largest(stream: list[int], k: int) -> list[int]:
h: list[int] = []
for x in stream:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return sorted(h, reverse=True)