Top K Frequent Words
Recognize the pattern
Brute force idea
If you approach Top K Frequent Words in the most literal way possible, you get this: Count frequencies, sort all words by frequency then alphabetically. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
Better approach
The real unlock in Top K Frequent Words comes when you notice this: Count frequencies with hash map, use a min-heap of size k with custom comparator (lower frequency first, higher alphabetical first for ties). 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 Words is this: The min-heap evicts the 'worst' candidate — lowest frequency, or alphabetically later for ties. After processing all words, the heap contains the top k in reverse order. As long as that statement keeps holding, you can trust the steps built on top of it.
Watch out for
The trap in Top K Frequent Words usually looks like this: Wrong tie-breaking in the heap comparator — for equal frequency, the lexicographically LARGER word should be at the top of the min-heap (to be evicted first), keeping the smaller word. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.