Stacks and heaps · Intermediate

Top K with a heap

Keep only the k best items in a heap of size k; each new item costs O(log k), so the k largest of n come out in O(n log k) without sorting everything.

On this page
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

The idea

To keep the k largest items, use a min-heap of size k. Its root is the smallest of the current top k, the one that is easiest to beat. A new item either loses to the root (ignore it) or replaces it (pop, push). After the scan the heap holds exactly the k largest.

The same structure gives "k closest points", "k most frequent words" (heap over counts) and merging k sorted lists (heap of the current head of each list). Two heaps, a max-heap for the lower half and a min-heap for the upper half, maintain a running median.

How to recognise it

  • "k largest", "k smallest", "k most frequent", "k closest".
  • A stream: items arrive one by one and you cannot store or sort all of them.
  • Merging several sorted sequences.
  • Repeatedly taking the current minimum or maximum while inserting new items (scheduling, simulation).

When not to use it

  • k is close to n: sorting is simpler and similar in cost.
  • You need only the single k-th element once and can modify the array: quickselect is expected O(n).
  • You need arbitrary removal or ordered iteration: a balanced search tree supports both.

Template

Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.

# k largest values of a stream
heap = min_heap()
for x in stream:
    if heap.size() < k:
        heap.push(x)
    elif x > heap.peek():
        heap.pop()
        heap.push(x)
return heap.items()              # unordered; sort them if order matters
  • Know your library default: C++ priority_queue is a max-heap, Python heapq, Java PriorityQueue and .NET PriorityQueue are min-heaps.
  • For a max-heap in a min-heap library, negate numeric keys or pass a reversed comparator.

Complexity

Time O(n log k), extra space O(k). Each of the n items does at most one pop and one push on a heap of size k. Building a heap of all n items is O(n), then k pops cost O(k log n), another valid option when memory allows.

Worked examples

Top 2 of [5, 1, 8, 3, 9]

Heap [5], then [1, 5]. 8 > root 1: replace → [5, 8]. 3 < root 5: ignore. 9 > 5: replace → [8, 9]. The two largest are 8 and 9.

Pitfalls

  • Using a max-heap of all items and popping k times when n is huge and arrives as a stream.
  • Assuming the heap iterates in sorted order (it does not).
  • Comparing objects without a consistent tie-breaker in languages that require total ordering.

Practise it

Solved problems with hints, a correctness argument and four tested implementations:

Learn the foundations

Related patterns

References

dsa.pattern.top-k-heap · version 1