Skip to solution
hardSystem Design

How would you design a typeahead/autocomplete system?

655 views
01

Understand the problem

Outline autocomplete.

autocompletetrie
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Step 1: Outline use cases and constraints

Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions.

Use cases

We'll scope the problem to handle only the following use cases

  • User performs core action described in How would you design a typ

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Trie with cached top-k suggestions
Run Playground
class Node:
    def __init__(self):
        self.children = {}
        self.top = []                 # cached (weight, word), best first

class Trie:
    def __init__(self, k=5):
        self.root = Node()
        self.k = k
    def insert(self, word, weight):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, Node())
            node.top = sorted(set(node.top + [(weight, word)]), reverse=True)[: self.k]
    def suggest(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return []
            node = node.children[ch]
        return [w for _, w in node.top]

t = Trie()
for word, freq in [("cat", 9), ("car", 7), ("cards", 3), ("dog", 5)]:
    t.insert(word, freq)
print("ca ->", t.suggest("ca"))   # ['cat', 'car', 'cards'] (by popularity)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 63 of 99 decoded in the System Design track. One more won't hurt.

Back to track