Top K Frequent Elements
Return the k values with highest frequencies.
Why does this pattern fit?
Restate the exact job
Return the k values with highest frequencies.
The answer depends on counts, then selecting only k extremes.
O(n log k) time · O(n) space
Building a max-heap of all values uses more ordering than needed.
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.