← Lessons

quiz vs the machine

Gold1400

Algorithms

The Top K Elements Pattern

Keep a small heap of size k to surface the largest or most frequent items.

5 min read · core · beat Gold to climb

You rarely need a full sort

When a problem asks for the k largest, k smallest, or k most frequent items, sorting everything is overkill. You only care about a handful of winners, so the top k elements pattern maintains a heap that holds exactly k candidates as you stream through the data.

The bounded heap trick

To find the k largest, keep a min heap of size k.

  • Push each new element onto the heap.
  • If the heap grows beyond k, pop the smallest, which is the heap top.
  • After processing everything, the heap holds the k largest, and its top is the kth largest.

The heap stays small, so each insert and removal touches only a shallow tree rather than the whole dataset.

Why a min heap for largest

It feels backward, but a min heap lets you cheaply evict the weakest surviving candidate. The smallest of your current winners sits right at the top, ready to be discarded the instant something better arrives. Frequency problems work the same way once you first count occurrences.

Key idea

Maintain a heap of size k so the weakest current winner sits at the top, letting you keep only the best candidates without sorting the whole input.

Check yourself

Answer to earn rating on the learn ladder.

1. To find the k largest elements, which heap do you keep?

2. Why is the top k pattern cheaper than fully sorting?

3. After processing every element, what does the heap top represent for the k largest task?