Browse curriculum

Top-K Elements Pattern

The Top-K elements pattern finds the K smallest, largest or most frequent elements in a dataset without fully sorting it.

SHELF OF 3

ADMIT

10

WEAKEST

The stream

10
5
20
3
8
40
2
50
60
1

 

10 arrives and the shelf is not full yet, so it goes straight in. Shelf: 10.

Next

5 arrives and the shelf is not full yet, so it goes straight in. Shelf: 5, 10.

Intuition

Suppose you want to find the top 10 richest people out of 8 billion. Sorting everyone is overkill!

Instead, we only care about maintaining a small list of the "best so far". The Top-K Elements pattern typically uses a Heap to track these elite items efficiently.

Concept

The Strategy:

  • K Largest: Use a Min-Heap of size K. If a new number is larger than the root (minimum of the top K), swap it.
  • K Smallest: Use a Max-Heap of size K. If a new number is smaller than the root (maximum of the bottom K), swap it.
  • QuickSelect: An alternative based on QuickSort partitioning (average O(N)).

How it Works

The visualizer shows items arriving one by one.

  1. A shelf holds K items.
  2. When a new item arrives, we compare it to the "weakest" item on the shelf.
  3. If the new item is better, the weak one is kicked out.

Step-by-Step Breakdown

1. Initialize Min-Heap of size 0.
2. For each num in array: heap.push(num).
3. If heap.size() > K: heap.pop() (remove smallest).
4. Result is the heap contents.

When to Use

  • "Find the K largest/smallest/most frequent..."
  • Streaming data (finding trends in real-time).
  • When K is much smaller than N (O(N log K) vs O(N log N)).

When NOT to Use

  • When K is close to N (Sorting might be faster due to constant factors).
  • When you need the exact rank of every element.

How to Identify

"Top K", "Kth largest", "Most frequent K items".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is the Top-K problem?

Finding the K largest, smallest, or most frequent items in a large, potentially infinite, data stream.


Heap vs Sort for Top-K?

Sorting is O(N log N). Using a heap of size K is O(N log K), which is significantly faster and more memory-efficient when K << N.


Priority Queue for Top-K?

A Min-Heap of size K can find the TOP K largest elements (as the root always contains the smallest of the "best" candidates).