Top-K Most Frequent Words With Tie-Breaking
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Tests ability to retrieve the k most frequent words from a list, using lexicographic order as a tie-breaker, via a heap or sort-based approach.
Top-K Most Frequent Words
You are building a tag-analytics dashboard. Given a list of word tags and a positive integer k, return the k most frequently occurring words, ordered by:
- Descending frequency (most frequent first).
- Ascending lexicographic order as a tie-breaker (so among words with the same count, alphabetically earlier words come first).
Return exactly k words. It is guaranteed that there are at least k distinct words in the input.
Constraints
1 <= len(words) <= 20001 <= k <= number of distinct words in words- Each word consists of lowercase English letters only (
a–z). 1 <= len(word) <= 20for each word inwords.- If multiple words share the same frequency, the one that comes earlier in lexicographic (alphabetical) order ranks higher.
Examples
Example 1
Input: top_k_frequent_words(['tag', 'bug', 'tag', 'fix', 'bug', 'tag'], 2)
Output: ['tag', 'bug']
Example 2
Input: top_k_frequent_words(['alpha', 'beta', 'gamma', 'alpha', 'beta', 'alpha'], 2)
Output: ['alpha', 'beta']
Example 3
Input: top_k_frequent_words(['zen', 'art', 'zen', 'art', 'pop'], 3)
Output: ['art', 'zen', 'pop']
Hints
Hint 1
Count frequencies with a dictionary or collections.Counter, then decide how to rank each word.
Hint 2
A (frequency, word) tuple can be sorted: sort by frequency descending and word ascending — try negating the frequency to turn it into a single ascending sort key.
Hint 3
A min-heap of size k works too: push (-freq, word) tuples so the heap naturally evicts the least-preferred entry, keeping the top k.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
The problem reduces to: count occurrences, then sort by a compound key.
Steps
-
Count frequencies using
collections.Counter(or a plaindict). This takes O(n) time and O(d) space where d is the number of distinct words. -
Sort the distinct words by the tuple
(-frequency, word):- Negating the frequency converts "descending frequency" into an ascending sort on the first key.
- The word itself (string) as the second key provides lexicographic tie-breaking in ascending order.
- Python's default tuple comparison handles both dimensions automatically.
-
Slice the first k elements of the sorted list and return.
Why it is correct
Python's sorted is stable and compares tuples lexicographically element-by-element. Using (-freq, word) as the key means:
- A higher frequency → smaller (more negative) first element → appears earlier.
- Equal frequency → second element (word) compared alphabetically → earlier word appears first.
This matches the problem's required ordering exactly.
Complexity
| Value | |
|---|---|
| Time | O(d log d) where d = number of distinct words (d ≤ n ≤ 2 000) |
| Space | O(d) for the counter and sorted list |
The overall runtime is dominated by counting (O(n)) and sorting (O(d log d)).
Reference Solution
from typing import List
from collections import Counter
def top_k_frequent_words(words: List[str], k: int) -> List[str]:
counts = Counter(words)
# Sort by (-frequency, word) so that higher frequency comes first
# and among equal frequencies, lexicographically smaller word comes first.
ranked = sorted(counts.keys(), key=lambda w: (-counts[w], w))
return ranked[:k]