Command Palette

Search for a command to run...

← All patterns

Pattern · Heaps

Top K with a Heap

Keep a heap of size k: a min-heap for the k largest, a max-heap for the k smallest.

Time O(n log k) · Space O(k)

Taught in Module 18: Heaps and Priority Queues

Think of it like this

A shortlist of the 3 tallest people seen so far: when someone taller arrives, the shortest person on the list is dropped.

Clues that point here

  • → "K largest", "K smallest", "K most frequent", "K closest"
  • → Kth largest element
  • → Stream of data with a top-K query

Not this pattern when

  • ✕ k is about n (just sort)
  • ✕ Only the single max (one variable)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Top K with a Heap · template
PriorityQueue<Integer> heap = new PriorityQueue<>();   // min-heap
for (int x : nums) {
    heap.offer(x);
    if (heap.size() > k) heap.poll();     // drop the smallest
}
return heap.peek();                       // kth largest

Common versions

  • Kth largest element
  • Top K frequent elements
  • K closest points to origin
  • Kth largest in a stream

Practice problems with this pattern

Related patterns