Heaps · Pattern 1 of 4

Top k, kth largest and repeatedly taking the best

Keep a min heap of size k: the top is the kth largest, and anything smaller than it can never make the cut. When you instead keep taking the biggest item and putting something back, use a max heap.

4 variations · 12 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Kth largest or smallest, or the k best, closest or most frequent items
  • A stream where the kth largest is asked after every new value
  • Take the two biggest (or smallest), combine them, and put the result back
  • Choose a team or a set of moves where only the best k so far should count

The template

Top K / Kth Largest / Smallest
// kth largest: a min heap that keeps the k largest values seen so far
int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>();
    for (int x : nums) {
        heap.offer(x);
        if (heap.size() > k) heap.poll();     // drop the smallest of the k + 1
    }
    return heap.peek();                       // the weakest of the k largest
}

// repeatedly take the best two and put back what is left: a max heap
int lastStoneWeight(int[] stones) {
    PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
    for (int s : stones) heap.offer(s);
    while (heap.size() > 1) {
        int a = heap.poll(), b = heap.poll();
        if (a != b) heap.offer(a - b);
    }
    return heap.isEmpty() ? 0 : heap.peek();
}

The variations

  1. 1A size-k heap for the kth largest

    Push every item and pop whenever the heap grows past k. What is left are the k best, and the top is the kth best. It works for a stream too: keep the heap between calls. "Best" can be the closest point or a student's top five scores.

  2. 2Count first, then take by frequency

    Count with a hash map, then put the counts in a heap. To remove the fewest distinct values, pop the rarest first; for the most frequent words or characters, pop the most common first.

  3. 3Repeatedly take the best and put it back

    A greedy simulation: pop the biggest (or the two smallest), change it, push the result back. Each round is O(log n), so k rounds cost O(k log n) instead of re-sorting every time.

  4. 4Keep the best k choices so far

    Walk the input in a useful order and keep a min heap of the choices that currently count. When the heap is over budget, the smallest choice is the one to give up: the slowest engineer, or the smallest climb that should use bricks instead of a ladder.

Mistakes to avoid

  • Using a max heap for "k largest": the top is then the best item, not the one to evict.
  • Comparing distances with a square root: compare squared distances, they keep the same order and stay integers.
  • In "maximum performance", forgetting to subtract the popped speed from the running sum.
Next: Custom comparators: ordering by several keys →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.