Top-K Most Frequent Words by Score
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Tests ability to rank words by a weighted frequency-length score, applying top-k selection with a precise tie-breaking rule.
Word Ranking by Score
You are building a search-relevance tool that scores words from a document and returns the most important ones.
Given a list of words and an integer k, compute a score for each unique word and return the top k words by score.
Scoring rule
For each unique word w, its score is:
score(w) = frequency(w) * len(w)
where frequency(w) is the number of times w appears in the input list (case-sensitive).
Tie-breaking
If two words have the same score, the word that comes earlier in lexicographic (alphabetical) order ranks higher.
Return a list of exactly k words in descending score order (highest score first), with ties broken as described.
Constraints
1 <= len(words) <= 20001 <= k <= number of unique words- Each word consists of lowercase English letters only.
1 <= len(w) <= 50for every wordw.- The answer is always unique given the tie-break rule.
Examples
Example 1
Input: top_k_words_by_score(['the', 'cat', 'sat', 'on', 'the', 'mat', 'the', 'cat'], 3)
Output: ['the', 'cat', 'mat']
Example 2
Input: top_k_words_by_score(['ab', 'ab', 'ab', 'cd', 'cd', 'efg'], 2)
Output: ['ab', 'cd']
Example 3
Input: top_k_words_by_score(['hello', 'world', 'hello', 'world', 'hello'], 1)
Output: ['hello']
Hints
Hint 1
Count the frequency of each word first, then compute score = frequency × word length for each unique word.
Hint 2
Use a sort key of (-score, word) so that higher scores come first and lexicographically smaller words break ties.
Hint 3
After sorting, simply slice the first k elements of the sorted list.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Plan
- Count frequencies using
collections.Counterin O(n) time. - Compute scores implicitly inside the sort key:
score(w) = freq[w] * len(w). - Sort unique words by the key
(-score, word):- Negating the score makes Python's default ascending sort put the highest scores first.
- Including the word itself as a secondary key breaks score ties lexicographically (ascending = lexicographically earlier first, which is what we want).
- Slice the first
kelements.
Why it is correct
The sort key (-score, word) is a total order over all unique words. Because Python's sort is stable and deterministic, the result is always unique — exactly matching the problem's tie-breaking requirement.
Complexity
| Value | |
|---|---|
| Time | O(n + u log u) where n = len(words), u = number of unique words |
| Space | O(u) for the Counter and sorted list |
Since u ≤ n ≤ 2000, this is very efficient.
from typing import List
from collections import Counter
def top_k_words_by_score(words: List[str], k: int) -> List[str]:
freq = Counter(words)
# Sort by (-score, word) so highest score first; ties broken lexicographically
ranked = sorted(freq.keys(), key=lambda w: (-(freq[w] * len(w)), w))
return ranked[:k]