LeetCode #692 Medium

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.

Constraints
  • 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]]
heaphash-mapsortingstring
Open on LeetCode ↗
02

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.
How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1import heapq
▶2from collections import Counter
▶3 
▶4class Entry:
▶5 def __init__(self, count, word):
▶6 self.count = count
▶7 self.word = word
▶8 
▶9 def __lt__(self, other):
▶10 if self.count != other.count:
▶11 return self.count < other.count
▶12 return self.word > other.word
▶13 
▶14class Solution:
▶15 def topKFrequent(self, words, k):
▶16 counts = Counter(words)
▶17 heap = []
▶18 for word, count in counts.items():
▶19 heapq.heappush(heap, Entry(count, word))
▶20 if len(heap) > k:
▶21 heapq.heappop(heap)
▶22 result = []
▶23 while heap:
▶24 result.append(heapq.heappop(heap).word)
▶25 return result[::-1]
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topemptyresultemptydroppednone4 distinct words counted
distinct4
k2
One pass over the 6 words gives each distinct word's count. From here on only these 4 words and their counts matter. The heap will keep at most 2 of them, with the weakest one on top.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topicount 2topresultemptydroppednonepush 'i' → it is the new top
wordicount 2
heap size1
'i' goes into the empty heap, so it is the top for now.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on toplovecount 2topicount 2resultemptydroppednonepush 'love' → it is the new top
wordlovecount 2
heap size2
'love' is the weakest word in the heap, so it rises to the top. 'love' and 'i' both appear 2 times, and 'love' comes later alphabetically.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topleetcodecount 1topicount 2lovecount 2resultemptydroppednonepush 'leetcode' → it is the new top
wordleetcodecount 1
heap size3
'leetcode' is the weakest word in the heap, so it rises to the top. 'leetcode' appears 1 time and 'love' 2.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on toplovecount 2topicount 2resultemptydroppedleetcode3 words, more than 2 → drop 'leetcode'
droppedleetcode
heap size2
The heap holds 3 words but only 2 can be kept. The top, 'leetcode', is weaker than the other 2, so at least 2 words beat it and it can never be in the answer. Pop it.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topcodingcount 1topicount 2lovecount 2resultemptydroppedleetcodepush 'coding' → it is the new top
wordcodingcount 1
heap size3
'coding' is the weakest word in the heap, so it rises to the top. 'coding' appears 1 time and 'love' 2.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on toplovecount 2topicount 2resultemptydroppedleetcodecoding3 words, more than 2 → drop 'coding'
droppedcoding
heap size2
The heap holds 3 words but only 2 can be kept. The top, 'coding', is weaker than the other 2, so at least 2 words beat it and it can never be in the answer. Pop it.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topicount 2topresultlovedroppedleetcodecodingpop 'love' → add it to the result
result[love]
Every word left is in the answer. The heap gives back the weakest first, so 'love' goes into the result first, although it belongs last.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topemptyresultloveidroppedleetcodecodingpop 'i' → add it to the result
result[love, i]
Every word left is in the answer. The heap gives back the weakest first, so 'i' goes into the result next.
countsi× 2love× 2leetcode× 1coding× 1min-heap · weakest on topemptyresultilovedroppedleetcodecodingreverse → i, love
result[i, love]
The pops came out weakest first, so reversing puts the strongest word first: highest count, and on a tie the alphabetically earlier word.
05

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.

▶1from collections import Counter
▶2 
▶3class Solution:
▶4 def topKFrequent(self, words, k):
▶5 counts = Counter(words)
▶6 ranked = sorted(counts, key=lambda w: (-counts[w], w))
▶7 return ranked[:k]
06

Common pitfalls

Using the answer's tie order inside the heap

✗ Wrong
heapq.heappush(heap, (count, word))
✓ Right
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

✗ Wrong
return [heapq.heappop(heap).word for _ in range(k)]
✓ Right
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

✗ Wrong
sorted(counts, key=lambda w: -counts[w])[:k]
✓ Right
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"].

07

Edge cases

Every word appears once

All counts tie, so only the alphabetical rule decides: the answer is the k words a dictionary would list first.

k equals the number of distinct words

The heap never reaches k + 1, nothing is evicted, and the answer is every distinct word in ranked order.

08

Complexity

Time
O(n log k)
Space
O(n)
n is the number of words. Counting is one pass. Each distinct word costs O(log k) to push and, past k, to pop; the final k pops cost O(k log k). The hash map holds up to n distinct words, and the heap never more than k + 1.
09

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.