Memory-Bounded Prefix Autocomplete with Fuzzy Backfill
Medium · Coding & Algorithms · Data Scientist · Technical Screen
Problem Statement
Design and implement a low-latency, memory-bounded prefix suggestion engine for a live marketplace search bar.
In production, the service indexes up to 5,000,000 UTF-8 catalog terms (including accented letters and hyphens), each paired with an integer popularity score refreshed hourly alongside ~1,000 live inserts, score updates, and deletions per second. As shoppers type keystrokes forming a prefix p at 5,000 queries per second, the service must return top-5 completions within < 20 ms p99 latency while staying inside a 300 MB resident memory budget.
Your solution should address both the architectural trade-offs (comparing compressed radix tries, ternary search trees, DAWGs, and binary-searched flat arrays; keeping per-prefix top-5 caches within 300 MB; supporting lock-free concurrent reads during dynamic writes; stable pagination; complexity; stress testing; and failure recovery) and implement the pure-Python engine defined in starter.py:
Entry = Tuple[int, str, str]: Canonical sort key(-score, normalized_key, display_word)so Python's ascending tuple comparison orders higherscorefirst, then lexicographicalnormalized_key, then lexicographicaldisplay_word.normalize(text: str) -> str: Applytext.casefold(), decompose via UnicodeNFKD, and strip combining marks (unicodedata.combining) while keeping hyphens and other base characters intact (for example,"Éclair-Glacé"becomes"eclair-glace").Autocomplete(words: Optional[Dict[str, int]] = None): Initialize the index from an optionaldisplay_word -> scoremapping (or empty).upsert(word: str, score: int) -> None: Insertwordor overwrite its integerscoreif already present. RaiseValueErrorifnormalize(word)is empty.delete(word: str) -> bool: Removewordand returnTrueif present, orFalseif absent.suggest(prefix: str) -> List[str]: Return up to5(TOP_K) display words whosenormalize(word)starts withnormalize(prefix), ranked inEntryorder. Whenever fewer than5exact-prefix matches exist, keep all exact matches first and fill the remaining slots (up to5total, without duplicates) with the highest-ranked other stored words that start with at least one string within Levenshtein edit distance 1 (one single-character insertion, deletion, or substitution) ofnormalize(prefix).page(prefix: str, after: Optional[Entry] = None, size: int = TOP_K) -> Tuple[List[str], Optional[Entry]]: Return one page(words, next_cursor)of exact-prefix matches strictly afterafter(or from the start whenafter is None) inEntryorder.next_cursoris the last returned word'sEntrywhen more exact matches remain, orNonewhen the page reaches the end. RaiseValueErrorifsize < 1.
Examples
Example 1
Input:
ac = Autocomplete({
"amethyst": 8, "amber": 5, "amulet": 5, "almond": 5,
"anklet": 5, "anvil": 3, "awl": 2, "brooch": 9,
})
ac.suggest("a")
ac.suggest("am")
Output:
ac.suggest("a") -> ["amethyst", "almond", "amber", "amulet", "anklet"]
ac.suggest("am") -> ["amethyst", "amber", "amulet", "almond", "anklet"]
Walk-through: For "a", seven words match; "amethyst" (score = 8) leads, followed by the four score = 5 words tied alphabetically ("almond", "amber", "amulet", "anklet"). For "am", only three exact matches exist ("amethyst", "amber", "amulet"), so two backfill slots are filled by words starting with a string 1 edit from "am" (deleting 'm' gives "a"), picking "almond" and "anklet". "brooch" (score = 9) requires 2 edits from "am" to any of its prefixes and is excluded.
Example 2
Input:
normalize("Éclair-Glacé")
ac = Autocomplete({"Piñata": 6, "pinata": 6, "piñatas": 9, "pine": 10})
ac.suggest("PIÑATA")
Output:
normalize("Éclair-Glacé") -> "eclair-glace"
ac.suggest("PIÑATA") -> ["piñatas", "Piñata", "pinata"]
Walk-through: casefold() + NFKD stripping folds "PIÑATA", "Piñata", and "pinata" to "pinata" and "piñatas" to "pinatas". "piñatas" (score = 9) ranks first; "Piñata" and "pinata" share (-6, "pinata", ...) and break ties by raw display string ('P' < 'p'). "pine" has no prefix within 1 edit of "pinata".
Example 3
Input:
ac = Autocomplete({"lamp": 4, "lantern": 7, "latch": 5, "lathe": 5})
p1, cur = ac.page("la", after=None, size=2)
ac.upsert("laser", 9)
removed = ac.delete("lamp")
p2, cur2 = ac.page("la", after=cur, size=2)
Output:
p1, cur -> (["lantern", "latch"], (-5, "latch", "latch"))
removed -> True
p2, cur2 -> (["lathe"], None)
Walk-through: Page 1 returns the top two "la" matches ("lantern", "latch") and keyset cursor (-5, "latch", "latch"). Inserting "laser" (score = 9) above the cursor does not shift or duplicate "latch", and deleting "lamp" leaves only "lathe" strictly after cur, so Page 2 returns (["lathe"], None).
Constraints
- Production design targets:
<= 5,000,000UTF-8 words,5,000QPS, p99 latency< 20 ms, memory<= 300 MB, and~1,000concurrentupsert/deleteupdates per second. - Scores are signed integers (higher means more popular);
TOP_K = 5. - Empty prefix
""matches every stored word inEntryorder. upsertraisesValueErrorifnormalize(word) == "";pageraisesValueErrorifsize < 1.- Readers (
suggest,page) must be safe to run concurrently alongsideupsertanddelete.
Step-by-step walkthrough
Clarify the rules and total ordering
Before picking a data structure, translate every product rule into something deterministic and testable:
- Unicode normalization: shoppers typing
"pinata","PIÑATA", or"pin\u0303ata"(where'n'and the combining tildeU+0303are stored as separate code points) expect the same suggestions. Unicode NFKD decomposition breaks accented characters into a base letter plus combining marks (floating accent symbols), andstr.casefold()converts text to caseless lowercase (including"ß"->"ss"). Dropping combining marks folds all three spellings into"pinata", while keeping ordinary symbols like hyphens ("Éclair-Glacé"->"eclair-glace"). - Strict total ordering: results rank by higher popularity
scorefirst, then alphabeticalnormalized_key, then alphabeticaldisplay_word(to break ties cleanly when both"Piñata"and"pinata"exist in the catalog). Storing each word as the tupleEntry = (-score, normalized_key, display_word)lets Python's default ascending tuple order sort highest scores first with zero ties between distinct words:
Word Score Entry = (-score, key, display_word) ---------- ----- ------------------------------------- "amethyst" 8 (-8, "amethyst", "amethyst") <- smallest tuple = rank #1 "Piñata" 6 (-6, "pinata", "Piñata") <- 'P' (80) < 'p' (112) = rank #2 "pinata" 6 (-6, "pinata", "pinata") <- rank #3- Edit-distance-1 backfill: if fewer than
5words start withnormalize(prefix), keep all exact matches first and fill the remaining slots with the highest-ranked other words that start with some string at Levenshtein edit distance 1 (one single-character insertion, deletion, or substitution) fromnormalize(prefix). - Pagination:
page(prefix, after, size)steps through exact-prefix matches in the sameEntryorder usingafteras a cursor, returning(words, next_cursor)wherenext_cursorisNoneon the final page.
- Unicode normalization: shoppers typing
Why naive approaches fail—and how 5M words fit in 300 MB
Scanning
5,000,000words on every keystroke at5,000queries per second requires2.5 * 10^10prefix checks per second—far too slow for< 20 msp99 latency. Compare the four candidate structures under our300 MBRAM ceiling:- Ternary Search Tree (TST): stores one node per character with three child pointers (
left,equal,right). Across5Mwords, tens of millions of pointer-heavy nodes exceed300 MBbefore storing any top-5 caches. - DAWG (Directed Acyclic Word Graph): merges shared suffixes as well as shared prefixes. That shrinks static dictionary size, but because multiple different prefixes merge into the same node, a node no longer represents a single prefix and cannot cache that prefix's top-5 words, nor can it handle
1,000live writes/sec without expensive graph splits. - Compressed (radix) trie: merges single-child chains so
5Mwords need at most2n = 10Mnodes. However, storing 5 int32 IDs (20 B) plus edge labels and child maps on all10Mnodes still pushes right past300 MB. - Sorted arrays + binary search: zero pointer overhead and
ceil(log2(5,000,000)) = 23comparisons to find the[low, high)index range of any prefix—but prefix"a"spans hundreds of thousands of words, so scanning the range to find the 5 highest scores is too slow, and inserting into a flat array isO(n).
The production design combines sorted flat arrays for a compact Base with a live copy-on-write Trie for a small Delta:
- Compact Base (~140 MB, rebuilt every ~5 minutes by shard): stores all
5Mnormalized keys in one contiguous byte array plusint32offsets andint32scores, and caches top-8 IDs in a hash table only for heavy prefixes—prefixes matching more thanT = 256words. Light prefixes (<= 256matches) just scan their tiny contiguous slice in microseconds! Because prefixes of lengthLhave disjoint ranges, fewer than5,000,000 / 256 ≈ 19,531prefixes at each length can be heavy (< 625,000across lengths1..32). Caching 8 instead of 5 absorbs deletions between rebuilds. - Live Delta (~30 MB in C++/Rust): a copy-on-write trie holding up to
300,000writes (5 min * 1,000 writes/s) plus a tombstone set of deleted/rescored base IDs. Queries merge Base + Delta inEntryorder, and background workers merge Delta into1/16th of the Base at a time so temporary memory stays well below300 MB.
Component Sizing for 5,000,000 words Memory ------------------------------- ---------------------------------- ------ Sorted normalized keys blob 5M * ~10 B average ~50 MB Key byte offsets (int32) 5M * 4 B 20 MB Popularity scores (int32) 5M * 4 B 20 MB Display strings != normalized ~20% of words * ~18 B ~18 MB Heavy-prefix (>256) top-8 table < 32 lengths * 19,500 * ~52 B ~32 MB Live copy-on-write Delta trie <= 300k recent updates * ~100 B ~30 MB Total resident footprint ~170 MB (<= 300 MB)In Python, object headers make any
5M-word structure multi-gigabyte, so ourAutocompleteclass below implements the self-contained copy-on-write trie engine directly (used as the Delta layer at5Mscale, or the entire index for in-memory catalogs).- Ternary Search Tree (TST): stores one node per character with three child pointers (
Normalize text and cache top-5 per trie node
A trie (prefix tree) is a tree where each edge is labeled with one character, so walking from the root along
"a" -> "m"lands on the single node representing every stored word that starts with"am".To make
suggestrun inO(|prefix|)time whenever at least 5 exact matches exist, every_Nodestorestop: the best5Entrytuples anywhere in its subtree. Crucially, recomputingnode.topnever scans the whole subtree—because each child already caches its own top 5,node.topis simply the top 5 amongnode.wordsandchild.topfor each child:[root] top: amethyst(8), almond(5), amber(5), amulet(5), anklet(5) | 'a' ["a"] top: amethyst(8), almond(5), amber(5), amulet(5), anklet(5) / \ 'l'/ \'m' ["al"] ["am"] top: amethyst(8), amber(5), amulet(5) | / | \ ["almond"(5)] .. .. .. -> amethyst(8), amber(5), amulet(5)from typing import Dict, List, Optional, Tuple import unicodedata TOP_K = 5 Entry = Tuple[int, str, str] def normalize(text: str) -> str: """Case-fold, NFKD-decompose, and strip combining accents: 'Piñata' -> 'pinata'.""" decomposed = unicodedata.normalize("NFKD", text.casefold()) kept_chars: List[str] = [] for ch in decomposed: if not unicodedata.combining(ch): kept_chars.append(ch) return "".join(kept_chars) class _Node: """Immutable-once-published trie node for copy-on-write concurrency.""" __slots__ = ("children", "words", "top") def __init__( self, children: Optional[Dict[str, "_Node"]] = None, words: Optional[Dict[str, Entry]] = None, ) -> None: # children: next normalized character -> child _Node self.children: Dict[str, _Node] = dict(children) if children else {} # words: display_word -> Entry for words whose normalized key ends here self.words: Dict[str, Entry] = dict(words) if words else {} # top: up to TOP_K best Entry tuples anywhere in this subtree, sorted best-first self.top: List[Entry] = [] def _copy_node(node: Optional[_Node]) -> _Node: """Shallow-copy a node's dicts so writers never mutate a published node.""" if node is None: return _Node() return _Node(node.children, node.words) def _compute_top_entries(node: _Node) -> List[Entry]: """Recompute the best TOP_K entries in `node`'s subtree from local + child caches.""" candidates: List[Entry] = list(node.words.values()) for child in node.children.values(): candidates.extend(child.top) candidates.sort() return candidates[:TOP_K]Lock-free concurrent reads via copy-on-write updates
If a writer mutates
node.childrenornode.topin place while 5,000 queries/sec walk the trie, a reader can see half-updated lists orRuntimeError: dictionary changed size during iteration. A reader-writer lock would prevent crashes, but write bursts would stall readers and hurt p99 latency.Instead, we use copy-on-write (path copying): once a
_Nodeis reachable fromself._root, it is never modified again. Whenupsert("awl", 10)runs: 1. Acquireself._write_lock(writers serialize against other writers so neither overwrites the other's update). 2. Record thelen(key) + 1existing nodes along"root -> a -> w -> l". 3. Rebuild only thoselen(key) + 1nodes from bottom to top, recomputingtopat each copied ancestor and dropping any non-root node left with zero words and zero children ondelete. Every untouched branch ("am...","b...") is shared by pointer with the old root! 4. Assignself._root = updated_childin one atomic reference swap.Old snapshot (in-flight readers keep walking this safely with zero locks): old_root ---> old_"a" ---> shared_"am" (amethyst, amber, amulet) \-------> old_"aw" ---> old_"awl"(2) New snapshot (published by `self._root = new_root`): new_root ---> new_"a" ---> shared_"am" (exact same _Node object in memory!) \-------> new_"aw" ---> new_"awl"(10)Because each reader grabs
root = self._rootonce at the start of a query, every query sees a linearizable snapshot—the exact state including all writes published before that moment and none after—with zero reader locking.def _write(self, word: str, score: Optional[int]) -> bool: key = normalize(word) if not key: if score is None: return False raise ValueError("word is empty after normalization") with self._write_lock: # Phase 1: record existing nodes along the root-to-key path. old_path: List[Optional[_Node]] = [self._root] for ch in key: parent = old_path[-1] if parent is not None: old_path.append(parent.children.get(ch)) else: old_path.append(None) target_node = old_path[-1] if score is None and (target_node is None or word not in target_node.words): return False # Phase 2: rebuild only the root-to-key path bottom-up; off-path subtrees stay shared. updated_child: Optional[_Node] = None for depth in range(len(key), -1, -1): new_node = _copy_node(old_path[depth]) if depth == len(key): if score is None: del new_node.words[word] else: new_node.words[word] = (-score, key, word) elif updated_child is None: new_node.children.pop(key[depth], None) else: new_node.children[key[depth]] = updated_child # Prune dead non-root nodes, keeping depth == 0 so _root is never None. if depth > 0 and not new_node.words and not new_node.children: updated_child = None else: new_node.top = _compute_top_entries(new_node) updated_child = new_node assert updated_child is not None self._root = updated_child return TrueEdit-distance-1 backfill with trie search
When
suggest(prefix)finds fewer than5exact matches, we need words that start with some stringqat Levenshtein edit distance 1 fromkey = normalize(prefix). Instead of generating every possible string over the whole Unicode alphabet,_fuzzy_nodeswalks existing trie edges with a 1-edit budget(node, index, edited):- No edit (
editedunchanged): follownode.children[key[index]]and advanceindex + 1. - Deletion from
key(!edited -> True): skipkey[index]while staying atnode(index + 1). Example:"cart"->"cat". - Insertion into
key(!edited -> True): follow any child(ch, child)without advancingindex. Example:"cat"->"chat". - Substitution (
!edited -> True): follow any child(ch, child)withch != key[index]and advanceindex + 1. Example:"cxt"->"cat".
Why don't we need an insertion after
index == len(key)(turning"cat"into"catx")? Because every word starting with"catx"already starts with"cat", so it was already returned in the exact-match step!def _find_node(root: _Node, key: str) -> Optional[_Node]: """Walk the trie along `key` and return the target node, or None if absent.""" node: Optional[_Node] = root for ch in key: assert node is not None node = node.children.get(ch) if node is None: return None return node def _fuzzy_nodes(root: _Node, key: str) -> List[_Node]: """Return distinct trie nodes whose path is at edit distance 1 from `key`.""" found: List[_Node] = [] found_ids: Set[int] = set() stack: List[Tuple[_Node, int, bool]] = [(root, 0, False)] while stack: node, index, edited = stack.pop() if index == len(key): if edited and id(node) not in found_ids: found_ids.add(id(node)) found.append(node) continue exact_child = node.children.get(key[index]) if exact_child is not None: stack.append((exact_child, index + 1, edited)) if not edited: stack.append((node, index + 1, True)) for ch, child in node.children.items(): stack.append((child, index, True)) if ch != key[index]: stack.append((child, index + 1, True)) return found- No edit (
Lazy best-first enumeration for backfill and pagination
Both fuzzy backfill (merging many near-miss subtrees while skipping exact hits) and pagination beyond item 5 need words ranked lazily, best-first, without scanning millions of descendants.
_ranked(starts)uses a min-heap seeded with(start.top[0], counter, start). Becausenode.top[0]is the smallest (best)Entryanywhere insidenode's subtree, no descendant ofnodecan beatnode.top[0]. Whenever we pop an item: - If it holds a_Node, we push all ofnode.words(marked withNoneinstead of a_Node) and push each child keyed bychild.top[0]. - If it holdsNone, thatEntryis guaranteed to be the best unyielded word across all start subtrees—yield it immediately! - Because fuzzy start nodes can overlap (for"am", deleting'm'reaches"a", which contains"al"reached by substituting'm' -> 'l'),expanded_node_idsensures no trie node is ever expanded twice, andcounterbreaks ties soheapqnever tries to compare two_Nodeinstances.def _ranked(starts: List[_Node]) -> Iterator[Entry]: """Lazily yield distinct entries under `starts` in best-first Entry order.""" heap: List[Tuple[Entry, int, Optional[_Node]]] = [] counter = 0 for start_node in starts: if start_node.top: heapq.heappush(heap, (start_node.top[0], counter, start_node)) counter += 1 expanded_node_ids: Set[int] = set() yielded_entries: Set[Entry] = set() while heap: entry, _, node = heapq.heappop(heap) if node is None: if entry not in yielded_entries: yielded_entries.add(entry) yield entry continue if id(node) in expanded_node_ids: continue expanded_node_ids.add(id(node)) for word_entry in node.words.values(): heapq.heappush(heap, (word_entry, counter, None)) counter += 1 for child in node.children.values(): if child.top: heapq.heappush(heap, (child.top[0], counter, child)) counter += 1Assemble suggest, keyset pagination, and trace Example 1
Offset pagination ("skip 5, take 5") breaks under live updates: if a high-scoring word like
"laser"(score = 9in Example 3) is inserted into page 1 while the shopper views it, item 2 ("latch") shifts down by one index and would repeat on page 2! A keyset cursor fixes this by passingafter = last_entry_on_previous_page((-5, "latch", "latch")) and keeping only entries strictly greater thanafter(entry > after). Fetchingsize + 1entries tells us whether another page exists without a second pass.Now trace
suggest("am")from Example 1 on{"amethyst": 8, "amber": 5, "amulet": 5, "almond": 5, "anklet": 5, "anvil": 3, "awl": 2, "brooch": 9}:1. Exact lookup for "am": exact_node.top = [(-8, "amethyst"), (-5, "amber"), (-5, "amulet")] (only 3 < 5 -> backfill 2 more!) 2. _fuzzy_nodes(root, "am") finds paths at edit distance 1 from "am": - delete 'm' -> "a" - substitute 'm' -> "al", "an", "aw" ("brooch" has prefixes "", "b", "br"... all >= 2 edits from "am", so never visited!) 3. _ranked(fuzzy_starts) expands "a" once (skipping re-expansion of "al", "an", "aw"): - yields (-8, "amethyst") -> in exact_set, skip - yields (-5, "almond") -> append! (4/5) - yields (-5, "amber") -> in exact_set, skip - yields (-5, "amulet") -> in exact_set, skip - yields (-5, "anklet") -> append! (5/5 -> stop!) Final output: ["amethyst", "amber", "amulet", "almond", "anklet"]def suggest(self, prefix: str) -> List[str]: root = self._root key = normalize(prefix) exact_node = _find_node(root, key) best_entries: List[Entry] = list(exact_node.top) if exact_node is not None else [] if len(best_entries) < TOP_K: exact_set = set(best_entries) fuzzy_starts = _fuzzy_nodes(root, key) for candidate in _ranked(fuzzy_starts): if candidate not in exact_set: best_entries.append(candidate) if len(best_entries) == TOP_K: break return _extract_words(best_entries) def page( self, prefix: str, after: Optional[Entry] = None, size: int = TOP_K, ) -> Tuple[List[str], Optional[Entry]]: if size < 1: raise ValueError("size must be at least 1") root = self._root exact_node = _find_node(root, normalize(prefix)) if exact_node is None: return [], None collected: List[Entry] = [] for entry in _ranked([exact_node]): if after is not None and entry <= after: continue collected.append(entry) if len(collected) > size: break if len(collected) > size: page_entries = collected[:size] return _extract_words(page_entries), page_entries[-1] return _extract_words(collected), NoneStress-testing strategy and production failure mitigations
Stress-testing strategy - Differential fuzzing: generate random mixes of accented/uppercase/hyphenated upserts, deletes,
suggest, andpagecalls against a slow brute-force oracle that computesmin(levenshtein(p, key[:j]))over every word (implemented intests.py). - Concurrency linearizability tests: run 16 reader threads continuously callingsuggestandpagewhile a writer thread streams 1,000 updates/sec, asserting no exceptions, duplicate entries, or out-of-order pages ever occur. - Latency & memory load tests: replay real keystroke distributions (including hot 1-letter prefixes, empty prefixes, 300-char shared prefixes, and typo-heavy prefixes that trigger backfill) at5,000QPS +1,000writes/s while measuring p99 latency and peak RSS memory during Base shard rebuilds.Edge-case & failure mitigations - Bound worst-case work: cap incoming prefixes at
64characters, reject malformed UTF-8 at the API gateway, cap pagination depth (for example, 10 pages), and enforce a step budget on_fuzzy_nodes/_rankedso pathological queries gracefully return partial exact matches rather than breaching the20 msSLA. - Crash recovery & stale-read fallback: persist Base shards to disk and append live updates to a Write-Ahead Log (WAL)—an append-only disk log replayed on startup. Run stateless replicas behind a load balancer; if the hourly score pipeline stalls, continue serving the last valid Base + Delta snapshot rather than returning errors.Complete solution
from typing import Dict, Iterator, List, Optional, Set, Tuple import heapq import threading import unicodedata TOP_K = 5 # Sort entry for one word: (-score, normalized_key, display_word). # Negating score lets Python's ascending tuple comparison rank higher popularity # first, then alphabetical normalized key, then alphabetical display word. # Example: (-8, "amethyst", "amethyst") < (-6, "pinata", "Piñata") < (-6, "pinata", "pinata"). Entry = Tuple[int, str, str] def normalize(text: str) -> str: """Case-fold, NFKD-decompose, and strip combining accents: 'Piñata' -> 'pinata'.""" # casefold() handles caseless matching (including 'ß' -> 'ss'); NFKD splits # accented letters like 'ñ' into base 'n' + combining mark U+0303. decomposed = unicodedata.normalize("NFKD", text.casefold()) kept_chars: List[str] = [] for ch in decomposed: if not unicodedata.combining(ch): kept_chars.append(ch) return "".join(kept_chars) class _Node: """Immutable-once-published trie node for copy-on-write concurrency.""" __slots__ = ("children", "words", "top") def __init__( self, children: Optional[Dict[str, "_Node"]] = None, words: Optional[Dict[str, Entry]] = None, ) -> None: # children: next normalized character -> child _Node (e.g. {'a': _Node, 'b': _Node}) self.children: Dict[str, _Node] = dict(children) if children else {} # words: display_word -> Entry for words whose normalized key ends at this node self.words: Dict[str, Entry] = dict(words) if words else {} # top: up to TOP_K best Entry tuples anywhere in this node's subtree, sorted best-first self.top: List[Entry] = [] def _copy_node(node: Optional[_Node]) -> _Node: """Shallow-copy a node's dicts so writers never mutate a published node.""" if node is None: return _Node() return _Node(node.children, node.words) def _compute_top_entries(node: _Node) -> List[Entry]: """Recompute the best TOP_K entries in `node`'s subtree from local + child caches.""" # Because every child's `top` already holds that child subtree's TOP_K winners, # the subtree's overall TOP_K must lie among `node.words` and `child.top` lists. candidates: List[Entry] = list(node.words.values()) for child in node.children.values(): candidates.extend(child.top) candidates.sort() return candidates[:TOP_K] def _find_node(root: _Node, key: str) -> Optional[_Node]: """Walk the trie along `key` and return the target node, or None if absent.""" node: Optional[_Node] = root for ch in key: assert node is not None node = node.children.get(ch) if node is None: return None return node def _fuzzy_nodes(root: _Node, key: str) -> List[_Node]: """Return distinct trie nodes whose path is at edit distance 1 from `key`.""" found: List[_Node] = [] found_ids: Set[int] = set() # stack holds (current_node, index_in_key, edit_already_used). stack: List[Tuple[_Node, int, bool]] = [(root, 0, False)] while stack: node, index, edited = stack.pop() # Once all characters of `key` are consumed, keep nodes that spent 1 edit. # Note: inserting an extra char *after* `key` (key + ch) is omitted here # because any word starting with `key + ch` already starts with `key` (exact match). if index == len(key): if edited and id(node) not in found_ids: found_ids.add(id(node)) found.append(node) continue # Branch 1: match key[index] with zero edits spent on this step. exact_child = node.children.get(key[index]) if exact_child is not None: stack.append((exact_child, index + 1, edited)) # If our single-edit budget is still unused, try all three 1-edit transitions: if not edited: # Edit A (deletion from key): skip key[index] while staying at `node`. stack.append((node, index + 1, True)) for ch, child in node.children.items(): # Edit B (insertion into key): advance in trie to `child` without advancing `index`. stack.append((child, index, True)) # Edit C (substitution): replace key[index] with a different character `ch`. if ch != key[index]: stack.append((child, index + 1, True)) return found def _ranked(starts: List[_Node]) -> Iterator[Entry]: """Lazily yield distinct entries under `starts` in best-first Entry order.""" # heap stores (best_entry_key, tie_breaker_int, node_or_None). # - When node_or_None is a _Node, best_entry_key is node.top[0] (the best entry # anywhere in its subtree—a tight lower bound on all entries inside it). # - When node_or_None is None, best_entry_key is an actual word Entry ready to yield. # - tie_breaker_int ensures Python never compares two _Node objects on equal Entry keys. heap: List[Tuple[Entry, int, Optional[_Node]]] = [] counter = 0 for start_node in starts: if start_node.top: heapq.heappush(heap, (start_node.top[0], counter, start_node)) counter += 1 # Fuzzy start nodes can overlap (e.g. "a" is an ancestor of "al"); tracking # expanded node IDs avoids expanding shared subtrees more than once. expanded_node_ids: Set[int] = set() yielded_entries: Set[Entry] = set() while heap: entry, _, node = heapq.heappop(heap) if node is None: if entry not in yielded_entries: yielded_entries.add(entry) yield entry continue if id(node) in expanded_node_ids: continue expanded_node_ids.add(id(node)) for word_entry in node.words.values(): heapq.heappush(heap, (word_entry, counter, None)) counter += 1 for child in node.children.values(): if child.top: heapq.heappush(heap, (child.top[0], counter, child)) counter += 1 def _extract_words(entries: List[Entry]) -> List[str]: """Unpack the display word (index 2) from each ranked Entry tuple.""" words: List[str] = [] for entry in entries: words.append(entry[2]) return words class Autocomplete: """Top-5 prefix suggestions with copy-on-write updates and edit-distance-1 backfill.""" def __init__(self, words: Optional[Dict[str, int]] = None) -> None: # Readers grab `self._root` lock-free; writers serialize on `self._write_lock` # and atomically swap `self._root` to a newly built path copy. self._root: _Node = _Node() self._write_lock = threading.Lock() if words: for word, score in words.items(): self.upsert(word, score) def upsert(self, word: str, score: int) -> None: """Insert word, or change its score if it is already present.""" self._write(word, score) def delete(self, word: str) -> bool: """Remove word. Return False if it was not present.""" return self._write(word, None) def _write(self, word: str, score: Optional[int]) -> bool: key = normalize(word) if not key: if score is None: return False raise ValueError("word is empty after normalization") with self._write_lock: # Phase 1: record existing nodes along the root-to-key path. # old_path[d] is the current _Node for key[:d], or None if missing. old_path: List[Optional[_Node]] = [self._root] for ch in key: parent = old_path[-1] if parent is not None: old_path.append(parent.children.get(ch)) else: old_path.append(None) target_node = old_path[-1] if score is None and (target_node is None or word not in target_node.words): return False # Phase 2: rebuild only the root-to-key path bottom-up; off-path subtrees stay shared. updated_child: Optional[_Node] = None for depth in range(len(key), -1, -1): new_node = _copy_node(old_path[depth]) if depth == len(key): if score is None: del new_node.words[word] else: new_node.words[word] = (-score, key, word) elif updated_child is None: new_node.children.pop(key[depth], None) else: new_node.children[key[depth]] = updated_child # Prune dead non-root nodes so deletes reclaim memory, while keeping # depth == 0 alive so `self._root` is always a valid _Node. if depth > 0 and not new_node.words and not new_node.children: updated_child = None else: new_node.top = _compute_top_entries(new_node) updated_child = new_node assert updated_child is not None # Single reference assignment publishes the new snapshot to concurrent readers. self._root = updated_child return True def suggest(self, prefix: str) -> List[str]: """Up to TOP_K words starting with prefix, backfilled with edit-distance-1 matches.""" # Capture one immutable root snapshot so exact and fuzzy steps see identical data. root = self._root key = normalize(prefix) exact_node = _find_node(root, key) best_entries: List[Entry] = list(exact_node.top) if exact_node is not None else [] if len(best_entries) < TOP_K: # Fewer than TOP_K exact matches means `exact_node.top` already holds ALL of them. exact_set = set(best_entries) fuzzy_starts = _fuzzy_nodes(root, key) for candidate in _ranked(fuzzy_starts): if candidate not in exact_set: best_entries.append(candidate) if len(best_entries) == TOP_K: break return _extract_words(best_entries) def page( self, prefix: str, after: Optional[Entry] = None, size: int = TOP_K, ) -> Tuple[List[str], Optional[Entry]]: """One page of exact-prefix matches using a stable keyset cursor.""" if size < 1: raise ValueError("size must be at least 1") root = self._root exact_node = _find_node(root, normalize(prefix)) if exact_node is None: return [], None # Collect up to `size + 1` entries strictly after `after` so we know whether # at least one more match remains without running a second query. collected: List[Entry] = [] for entry in _ranked([exact_node]): if after is not None and entry <= after: continue collected.append(entry) if len(collected) > size: break if len(collected) > size: page_entries = collected[:size] return _extract_words(page_entries), page_entries[-1] return _extract_words(collected), None✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a giant catalog organized as a branching hallway of letter signs—a trie (prefix tree), where walking past sign 'p', then 'i', then 'n' leads to the single alcove holding every item starting with "pin". If we post a tiny leaderboard on every sign listing the 5 most popular items anywhere down that hallway, answering "pin" takes just three steps and reading the sign—we never walk into the thousands of rooms further down. And when a writer updates an item's popularity score, instead of erasing signs while shoppers are reading them, they print fresh signs only along that single hallway and swap the main entrance sign in one instant (copy-on-write), so readers already inside see a consistent snapshot with zero waiting.
Naive designs fail on latency, memory, or concurrency. Scanning all 5,000,000 terms at 5,000 queries per second requires 25 billion prefix checks per second; binary-searching a sorted array finds "a..." in 23 steps, but still has to scan hundreds of thousands of "a" words to pick the top 5 scores; and caching top-5 lists on every node of an uncompressed 5M-word trie exceeds 300 MB of RAM—which is why at 5M scale we pair a compact ~140 MB sorted-array Base (caching top lists only for "heavy" prefixes with > 256 matches) with our ~30 MB copy-on-write Delta trie for live updates.
Walk through a 4-item trace with {"amethyst": 8, "amber": 5, "almond": 6, "brooch": 9} when the user types "am":
- Normalize & exact lookup: "am" walks 'a' -> 'm', reading exact_node.top = [(-8, "amethyst", "amethyst"), (-5, "amber", "amber")]. Only 2 exact hits exist (< 5), so we trigger backfill.
- Edit-distance-1 trie walk: _fuzzy_nodes explores paths one insertion, deletion, or substitution from "am", reaching "a" (by deleting 'm') and "al" (by substituting 'm' -> 'l'), while "brooch" ("b...") is 2 edits away and ignored.
- Best-first ranking: _ranked seeds a min-heap (a binary tree whose root is always the smallest—best—Entry tuple) with node.top[0], expands "a" once without re-expanding "al", skips "amethyst" and "amber" (already in exact hits), and appends "almond" to return ["amethyst", "amber", "almond"].
Complexity
Let P be the prefix length, L the word length, K = 5, B the maximum branching factor (number of children at a visited node), W the maximum number of display variants sharing one normalized key, and D the maximum word depth below a start node.
suggest(when>= 5exact matches exist) —O(P + K)time: We normalize the prefix and followPdictionary lookups down the trie inO(P)time, then copyK = 5pre-sorted entries fromexact_node.topinO(K)time without touching any descendants.suggest(with edit-distance-1 backfill) —O(B * P^2 + (F + K * D) * (B + W) * log H)time:_fuzzy_nodesvisits at mostP + 1unedited prefix positions, branches into at most2B + 1single-edit states at each position, and follows at mostPexact characters afterward (O(B * P^2)). Then_rankedneeds at mostKdistinct words; because every node is keyed by its subtree's best word (node.top[0]) andexpanded_node_idsexpands each trie node at most once, at mostFduplicate start pops plusK * Dancestor nodes are expanded, each pushing up toB + Witems onto a heap of sizeH.page(returningsizeitems afterSskipped items) —O(P + (S + size) * D * (B + W) * log H)time: Walking to the prefix node takesO(P), and best-first enumeration expands only ancestors of theS + size + 1highest-ranked exact matches rather than sorting the entire subtree.upsertanddelete—O(L * (W + B * K) * log(W + B * K))time: Copy-on-write copiesL + 1nodes along the root-to-key path, and at each copied node sorts at mostW + B * Kcandidate entries to rebuild itstoplist of lengthK.- Space —
O(total characters across distinct prefixes * K)for the trie (and~170 MBin the two-tier Base + Delta architecture for5Mwords): Each trie node stores child references plus up toK = 5tuple references, and each write allocates onlyL + 1copied nodes while sharing all off-path subtrees; at5M-word production scale, flat sorted arrays + heavy-prefix (> 256) top-8 caches (~140 MB) plus the bounded300k-entry Delta trie (~30 MB) stay comfortably inside the300 MBRAM limit.
Edge cases
- Empty prefix (
""): normalizes to"", returningself._root.top—the global top 5 across all stored words (or[]when the dictionary is empty). - Single-character prefix with
< 5matches (e.g."q"): deleting'q'yields""at edit distance 1, so backfill pulls from the global top 5; if product UX prefers not to backfill from"", require fuzzy target paths to have length>= 1. - Words that normalize to empty (
""or lone combining accent"\u0301"):upsertrejects them withValueErrorso phantom empty keys never pollute the root, whiledeletesafely returnsFalse. - Multiple display spellings sharing one key (
"Piñata"and"pinata"): stored side by side innode.wordskeyed by display string, withEntry = (-score, key, word)breaking ties deterministically by Unicode code-point order ("Piñata"before"pinata"). - Characters NFKD does not fold to ASCII: Unicode NFKD strips combining accents (
ñ -> n,é -> e), andcasefold()expandsß -> ss, whereas stroke/ligature letters without compatibility decompositions (ø,ł,æ, Turkish dotlessı) remain distinct unless an explicit transliteration map is added. - Deleting the final word in the dictionary: non-root empty nodes (
depth > 0) are pruned to prevent memory leaks, whiledepth == 0is preserved soself._rootis always a valid_Node. - Very long shared prefixes (e.g. 300
'x'characters): an uncompressed trie walks 300 nodes and_fuzzy_nodestakesO(B * P^2); production services cap query prefix length (for example at 64 chars) and compress single-child chains into a radix trie.
Common mistakes
- Using NFC instead of NFKD during normalization: NFC composes characters into single code points (
'ñ'), so filteringnot unicodedata.combining(ch)removes nothing and"pinata"fails to match"piñata". - Mutating
children,words, ortopin place during writes: mutating a published dictionary while reader threads iterate over it causes torn reads or runtime exceptions; copy-on-write must shallow-copy every modified node on the path. - Trying to serve page 2 from
node.topor withOFFSET:node.toponly caches5items, and integer offsets repeat or skip suggestions when concurrentupsert/deletecalls shift rankings above the page boundary; use lazy best-first_rankedwith a keyset cursor (entry > after). - Allowing fuzzy backfill to outrank or duplicate exact matches: a popular typo neighbor like
"cat"(score = 100) must still appear after exact match"cake"(score = 3) for prefix"cak", andexact_setmust filter exact words out of_ranked(fuzzy_starts). - Pushing
(entry, node)directly ontoheapqwithout an integer tie-breaker: if two sibling subtrees somehow shared an identical tuple prefix or during custom extensions, Python would attemptnode1 < node2and raiseTypeError: '<' not supported between instances of '_Node' and '_Node'.
Alternative approaches
- Hash map of every prefix to its precomputed top 5: gives
O(1)exact lookups, but5,000,000words average3+unique prefixes per word (15M+map entries), blowing past300 MBon keys, hash buckets, and 5-ID arrays alone—plus every score update must touchLhash entries. - Weighted Finite-State Transducer (WFST, as used in Lucene's analyzing suggester): compresses both shared prefixes and shared suffixes with edge weights so static lookup is tiny in RAM, at the cost of requiring periodic offline rebuilds paired with a live Delta trie for
1,000writes/sec. - SymSpell (symmetric-delete dictionary) for typos: pre-indexes all 1-deletion substrings of keys for fast lookup, which works well for whole-word spellcheck, whereas prefix matching would require indexing deletions of every prefix of every word (
O(L^2)entries per word), exceeding300 MB.
Follow-up questions
- How could you extend fuzzy backfill to catch adjacent-character swaps such as typing 'teh' for 'the'? Support Damerau-Levenshtein distance 1 by adding one extra branch inside
_fuzzy_nodeswhenevernot edited and index + 1 < len(key) and key[index] != key[index + 1]: step fromnodealongkey[index + 1]tomid_node, then alongkey[index]toswapped_node, and push(swapped_node, index + 2, True). Becauseswapped_nodeis an ordinary trie node,_ranked, deduplication, andEntrytie-breaking require zero changes. - How would you partition the index across machines if the catalog expanded to 100 million terms? Partition terms across shards by normalized 2- or 3-character prefix range so any query of length
>= 3routes directly to a single shard for exact matches, while keeping a tiny replicated cache of global top-5 lists for prefixes of length0..2on every router node. Only queries needing edit-distance-1 backfill where the edit occurs inside the first 2–3 characters need scatter-gather across neighboring shards, keeping p99 tail latency low compared to hash sharding (which forces scatter-gather on every keystroke). - How would you incorporate per-user ranking signals without duplicating the prefix index for every user? Keep one shared global index ranked by global popularity, pull the top
50candidates lazily using_ranked(increasingnode.topor running a bounded 50-pop best-first walk), and re-score just those50candidates in< 1 msusing lightweight user features such as recent shop/category clicks or locale, breaking final ties with the same deterministic(-final_score, key, word)tuple.
Follow-up questions
- How could you extend fuzzy backfill to catch adjacent-character swaps such as typing 'teh' for 'the'?
- How would you partition the index across machines if the catalog expanded to 100 million terms?
- How would you incorporate per-user ranking signals without duplicating the prefix index for every user?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array