PROBLEM 33 OF 75

Top K Frequent Elements

Return the k values with highest frequencies.

PATTERNHeaps & ordered selectionA heap exposes the next extreme, not the whole order.
SPOT THE SIGNAL

Why does this pattern fit?

FRAME · 1 OF 4

Restate the exact job

Return the k values with highest frequencies.

WHY THIS FITS

The answer depends on counts, then selecting only k extremes.

COMPLEXITY

O(n log k) time · O(n) space

COMMON FAILURE

Building a max-heap of all values uses more ordering than needed.

THE REASONING, IN ONE PLACE

How to solve Top K Frequent Elements

The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.

What the question asks

Return the k values with highest frequencies.

Why Heaps & ordered selection fits

The answer depends on counts, then selecting only k extremes.

State to maintain

A frequency map and a min-heap of at most k entries.

Transition

Push counts and pop the smallest whenever heap size exceeds k.

Time and space

O(n log k) time · O(n) space

Counterexample to the tempting mistake

Building a max-heap of all values uses more ordering than needed.

Prove it again tomorrow

Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.

Open blank recall ↗