Top K Frequent Words
Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #692
Return the k most frequent words, sorted by frequency from highest to lowest. Words with the same frequency are ordered lexicographically.
Examples
text
words = ["i","love","leetcode","i","love","coding"], k = 2 → ["i","love"]
words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
→ ["the","is","sunny","day"]Hints
- Count with a hash map first.
- Sorting by the key
(-count, word)is the simple O(n log n) solution. For O(n log k), keep a heap of size k, and think about which element should be evicted first.
Approach
cnt = Counter(words).- Simple: sort the unique words by
(-cnt[w], w)and take the first k. - Heap of size k (O(n log k)): keep the k best words in a min-heap whose top is the worst of them. "Worst" means a lower count, or, on a tie, the lexicographically larger word. Python's tuple ordering can't reverse string order directly, so either wrap the word in a class with an inverted
<, or just useheapq.nsmallest(k, cnt, key=lambda w: (-cnt[w], w)), which runs in O(n log k).
Getting the tie-break direction wrong inside the heap is the classic bug in this problem.
Complexity
Time: O(n log k) with the heap (O(n log n) with a sort). Space: O(n).
Python solution
from collections import Counter
import heapq
def topKFrequent(words, k):
cnt = Counter(words)
return heapq.nsmallest(k, cnt.keys(), key=lambda w: (-cnt[w], w))JavaScript solution
function topKFrequent(words, k) {
const cnt = new Map();
for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1);
return [...cnt.keys()]
.sort((a, b) => cnt.get(b) - cnt.get(a) || (a < b ? -1 : a > b ? 1 : 0))
.slice(0, k);
}