Skip to content
GKgkml.dev
← Pattern lab

Heaps and top-k

Keep a size-k heap instead of sorting everything.

The tell: 'k largest', 'k closest', 'median of a stream', 'merge k sorted lists'.

Reach for it when

  • k largest / smallest elements
  • k most frequent elements
  • Merging k sorted lists
  • Running median with two heaps
  • Dijkstra's shortest path

Reference implementation

top_k — min-heap of size k
import heapq

def top_k(nums: list[int], k: int) -> list[int]:
    """The k largest values. Python's heapq is a MIN-heap."""
    heap: list[int] = []
    for value in nums:
        if len(heap) < k:
            heapq.heappush(heap, value)
        elif value > heap[0]:
            # heap[0] is the smallest kept so far — evict it.
            heapq.heapreplace(heap, value)
    return sorted(heap, reverse=True)

Complexity: O(n log k) for top-k, versus O(n log n) for a full sort.

What goes wrong

  • Forgetting `heapq` is a min-heap: for a max-heap, push `-value` or a `(-priority, item)` tuple.
  • Pushing a tuple whose second element is not comparable — ties then raise TypeError.
  • Using `heappush` + `heappop` where `heapreplace` does both in one sift.

Practise on

  • Kth Largest Element in an Array
  • Top K Frequent Elements
  • Merge k Sorted Lists
  • Find Median from Data Stream