Top K Frequent Words (LeetCode 692): Solution and Explanation
Given a list of words and a number k, return the k most frequent words. Order them by frequency from high to low, and break ties by putting the alphabetically smaller word first.
Intuition
Two separate jobs hide in this problem. First you need each word's frequency, which a hash map gives you in one pass. Then you need the first k words under a specific order: count descending, and word ascending when counts tie.
That order is the whole difficulty. If you only rank by count, ties come out in an arbitrary order and the answer is wrong. So every comparison must check the counts first and fall back to comparing the words.
A heap built on that comparison always keeps the best remaining word at its root. Popping the root k times hands out the answer in exactly the order the problem asks for, with no extra sorting step.
In Python the tuple (-count, word) encodes the rule for free: negating the count turns the min-heap into highest-count-first, and tuples compare the word second, alphabetically.
Approach: Count map plus a heap ranked by (count desc, word asc)
- Count every word with a hash map.
- Push one entry per distinct word into a heap that ranks higher counts first and, on equal counts, the alphabetically smaller word first.
- Pop the root
ktimes. Each pop removes the best remaining word and the heap re-sifts to bring the next best to the top. - Return the popped words in the order they came out.
Step-by-step example
words = ["i","love","leetcode","i","love","coding"], k = 2
- Counting gives i: 2, love: 2, leetcode: 1, coding: 1.
- Push i(2), then love(2). love ties with i on count but comes later alphabetically, so it stays below i.
- Push leetcode(1) and coding(1) as leaves; neither outranks its parent.
- Pop the root i(2). The last leaf moves to the root and sinks, which brings love(2) to the top.
- Pop love(2). Two words have been popped, so the answer is ["i", "love"].
Code: Python, Java, C++
1class Solution:
2 def topKFrequent(self, words: List[str], k: int) -> List[str]:
3 count = Counter(words)
4 heap = []
5 for word, freq in count.items():
6 heapq.heappush(heap, (-freq, word))
7 result = []
8 for _ in range(k):
9 freq, word = heapq.heappop(heap)
10 result.append(word)
11 return result1class Solution {
2 public List<String> topKFrequent(String[] words, int k) {
3 Map<String, Integer> count = new HashMap<>();
4 for (String w : words) count.merge(w, 1, Integer::sum);
5 PriorityQueue<String> heap = new PriorityQueue<>((a, b) ->
6 count.get(a).equals(count.get(b)) ? a.compareTo(b) : count.get(b) - count.get(a));
7 for (String w : count.keySet()) heap.offer(w);
8 List<String> result = new ArrayList<>();
9 for (int i = 0; i < k; i++) {
10 result.add(heap.poll());
11 }
12 return result;
13 }
14}1class Solution {
2public:
3 vector<string> topKFrequent(vector<string>& words, int k) {
4 unordered_map<string, int> count;
5 for (const string& w : words) count[w]++;
6 auto cmp = [&](const string& a, const string& b) {
7 return count[a] == count[b] ? a > b : count[a] < count[b];
8 };
9 priority_queue<string, vector<string>, decltype(cmp)> heap(cmp);
10 for (auto& p : count) heap.push(p.first);
11 vector<string> result;
12 for (int i = 0; i < k; i++) {
13 result.push_back(heap.top());
14 heap.pop();
15 }
16 return result;
17 }
18};Time and space complexity
O(n + m log m)
Counting reads all n words once. Building the heap from m distinct words costs O(m log m) with pushes, and the k pops cost O(k log m).
O(m)
The count map and the heap each hold one entry per distinct word.
Other approaches
Sort the distinct words (time O(n + m log m), space O(m))
Sort the distinct words with the key (-count, word) and take the first k. It is short and clear, and its cost is the same O(m log m) as building a full heap.
Heap of size k (time O(n + m log k), space O(m))
Keep at most k entries in a heap whose root is the worst kept entry (lowest count, alphabetically last on ties). When it grows past k, pop the root. At the end, pop everything and reverse. This is the O(n log k) follow-up, but the inverted tie rule is easy to get wrong.
Bucket by count (time O(n + m log m) in the worst case, space O(n))
Put each word in a bucket indexed by its count, sort each bucket alphabetically, and read buckets from the highest count down until k words are collected.
Common mistakes
- Ranking by count only. Words with equal counts must come out alphabetically, so the comparator needs the second key.
- Flipping the tie rule in a size-k min-heap. There the root must be the alphabetically larger word, the opposite of the final order.
- Using a locale-aware string compare. Plain ordinal comparison matches what the problem means by lexicographical order.
- Returning the heap's internal array. Only the pop order is sorted; the array itself is only partially ordered.
Frequently asked questions
Why does the heap need both the count and the word?
Many words share a count. Without the word as a second key, the heap may return tied words in any order, and the expected answer fixes that order alphabetically.
How is this different from Top K Frequent Elements?
Top K Frequent Elements accepts the answer in any order. Here the order is part of the answer, both by count and alphabetically on ties, so the comparison rule matters.
Can I get better than O(m log m)?
Yes. A heap capped at k entries runs in O(n + m log k), which helps when k is much smaller than the number of distinct words.
What is the time complexity of Top K Frequent Words?
Counting is O(n). With a full heap or a sort it is O(m log m) on top of that, and with a size-k heap it is O(m log k), where m is the number of distinct words.