---
title: Prefix autocomplete ranked by popularity
url: https://gurkanozkan.ai/learn/coding/mle-prefix-autocomplete-ranked-by-popularity-37/
markdown: https://gurkanozkan.ai/learn/coding/mle-prefix-autocomplete-ranked-by-popularity-37.md
kind: coding
difficulty: Easy
topics:
  - Trie
  - Strings
  - Search
json: https://gurkanozkan.ai/api/learn/coding/mle-prefix-autocomplete-ranked-by-popularity-37.json
robots: noindex
---

# Prefix autocomplete ranked by popularity

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

```python
def autocomplete(word_freqs: dict[str, int], prefix: str, k: int) -> list[str]: ...
```

## Examples

Each call and the value it should give.

```python
>>> autocomplete({'banana': 5, 'band': 9, 'bandana': 9, 'apple': 20}, 'ban', 2) == ['band', 'bandana']
True

>>> autocomplete({'banana': 5, 'band': 9}, 'x', 3) == []
True
```

## Hints

1. Sort by frequency desc, then alphabetically; take prefix matches.
2. An empty prefix matches everything; use heapq.nsmallest for O(m log k).
3. At scale, per-node top-k cached trie nodes beat a full scan.

## Reference solution

```python
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.nsmallest` for 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).
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
