Prefix autocomplete ranked by popularity
Problem
Return up to k words from word_freqs that start with prefix, sorted by frequency descending, then alphabetically. An empty prefix matches every word.
Signature
def autocomplete(word_freqs: dict[str, int], prefix: str, k: int) -> list[str]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> autocomplete({'banana': 5, 'band': 9, 'bandana': 9, 'apple': 20}, 'ban', 2) == ['band', 'bandana']
True
>>> autocomplete({'banana': 5, 'band': 9}, 'x', 3) == []
TrueHints
Sort by frequency desc, then alphabetically; take prefix matches.
An empty prefix matches everything; use heapq.nsmallest for O(m log k).
At scale, per-node top-k cached trie nodes beat a full scan.
Reference solution
def autocomplete(word_freqs, prefix, k):
cands = [(-f, w) for w, f in word_freqs.items() if w.startswith(prefix)]
cands.sort()
return [w for _, w in cands[:k]]What a strong solution covers
- Correct ordering key
(-freq, word). - Trie with per-node cached top-k for O(len(prefix)) queries;
heapq.nsmallestfor O(m log k). - Discusses update cost and personalisation.
Common mistakes
- sorting by frequency only, so ties come out in nondeterministic order
- scanning all words per keystroke at scale (discussion).