Top K Frequent Words
Top K Frequent Words is LeetCode 692 (Medium). Given an array of lowercase words and an integer k, return the k most frequent words.
- Sort the answer by frequency, highest first.
- Words with the same frequency go in lexicographical order, the order a dictionary lists them in.
k is never more than the number of distinct words. The follow-up asks for O(n log k) time, so sorting every distinct word is not the target answer.
- 1 <= words.length <= 500
- 1 <= words[i].length <= 10
- words[i] consists of lowercase English letters.
- k is in the range [1, The number of unique words[i]]
Intuition
Rank words by one rule: a word is stronger if it appears more often, or, on a tie, if it comes first alphabetically. The answer is the k strongest words, strongest first.
To find them without sorting everything, keep a min-heap of size k whose top is the weakest word kept. Each word goes in; when the heap reaches k + 1 words, pop the top. That word is weaker than k others, so it can never make the answer.
- The heap's order is the answer's order turned around: lower count on top, and on a tie the alphabetically later word on top.
- Popping gives the answer backwards, so reverse it at the end.
"Return the k largest by some score" with a small k is a bounded heap: keep k candidates and throw out the worst each time a new one arrives. A tie-break that runs the opposite way to the score means the heap needs its own comparator.
Approach
Before reading on, decide which word a heap of the best k should throw out when two words have the same count. Then work out what order the heap hands its words back in. Aim for O(n log k) time.
Two ways to solve it
Keep the k strongest words seen so far and throw out the weakest whenever a new word pushes the heap past k.
- Meets the follow-up: O(n log k).
- Watch out: the heap's tie order is the reverse of the answer's.
The answer interviewers ask for.
Sort the distinct words by count, highest first, then alphabetically, and take the first k.
- Shortest code: one sort with a two-part key.
- Cost: sorts words that can never make the answer.
The obvious first idea, and fast enough at 500 words.
Both count the words first. The heap keeps only k candidates, so it does O(log k) work per word; the sort ranks every distinct word. The steps, code and live demo follow the heap, and the sorting code comes after the demo.
Count every word
Build a hash map from word to count in one pass. The ranking only looks at each word and its count, so after this pass the original array is no longer needed.
Define which word is weaker
Word a is weaker than b if its count is lower, or the counts tie and a comes later alphabetically. A Python tuple compares both parts in the same direction, so a small class with __lt__ states the rule; C++ and Java pass it as a comparator.
Push each word and evict past k
Push every distinct word. When the heap holds k + 1 words, pop the top. The k words left are all stronger than the one popped, so it cannot be in the top k, and the heap never holds more than k + 1 words.
Pop the survivors and reverse
Pop the k remaining words one by one. A min-heap hands them back weakest first, so reverse the list to get the strongest word first, which is the order the answer needs.
Code in Python, C++ and Java
Sort every distinct word
Sort the distinct words with a two-part key: count from high to low, then the word from A to Z. The first k words of the sorted list are the answer, already in the right order.
Common pitfalls
Using the answer's tie order inside the heap
heapq.heappush(heap, (count, word))
heapq.heappush(heap, Entry(count, word))
With plain (count, word) tuples, a tie puts the alphabetically earlier word on top, so it is the one thrown out. On ["cat", "dog", "ant", "dog", "ant", "cat"] with k = 2 all three words tie at 2, ant is evicted, and the result is ["dog", "cat"] instead of ["ant", "cat"].
Returning the words in the order the heap pops them
return [heapq.heappop(heap).word for _ in range(k)]
result = [heapq.heappop(heap).word for _ in range(k)] return result[::-1]
The top of the heap is always the weakest word, so pops come out weakest first. On ["i", "love", "leetcode", "i", "love", "coding"] with k = 2 this returns ["love", "i"], but i comes first alphabetically and must lead.
Sorting by count alone
sorted(counts, key=lambda w: -counts[w])[:k]
sorted(counts, key=lambda w: (-counts[w], w))[:k]
A stable sort keeps tied words in the order they first appeared, not alphabetical order. On ["b", "a"] with k = 1 it returns ["b"], but the answer is ["a"].
Edge cases
All counts tie, so only the alphabetical rule decides: the answer is the k words a dictionary would list first.
The heap never reaches k + 1, nothing is evicted, and the answer is every distinct word in ranked order.
Complexity
Top K Frequent Words FAQ
How is this different from Top K Frequent Elements?
LeetCode 347 returns numbers in any order, so only the counts matter and bucket sort by count finishes in O(n). Here the order is fixed and ties are broken alphabetically, so every bucket would still need sorting. That brings back a log factor, which is why the heap or a plain sort is the usual answer for words.
Can Python's heapq do this in one line?
Yes: heapq.nsmallest(k, counts, key=lambda w: (-counts[w], w)). The key is smallest for the strongest word, and nsmallest keeps only k candidates while it scans, so it also runs in O(n log k). nlargest does not work as easily, because the alphabetical tie-break would need a negated string.