Top K Frequent Elements
Recognize the pattern
Brute force idea
The naive version of Top K Frequent Elements sounds like this: Count frequencies, sort by frequency, take top k. Sorting is overkill when you only need the top k. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
Better approach
The real unlock in Top K Frequent Elements comes when you notice this: Count frequencies with a hash map, then use a min-heap of size k to track the top k elements. — the heap never grows beyond k elements. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Key invariant
The compass for Top K Frequent Elements is this: The min-heap's smallest element is always the threshold — if a new frequency is larger, swap it in. After processing all elements, the heap contains exactly the k most frequent. As long as that statement keeps holding, you can trust the steps built on top of it.
Watch out for
A common way to get lost in Top K Frequent Elements is this: Using a max-heap — that finds the maximum, not the top k. A min-heap of size k naturally evicts the smallest, keeping only the largest k frequencies. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.