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 higher score first, then lexicographical normalized_key, then lexicographical display_word.
  • normalize(text: str) -> str: Apply text.casefold(), decompose via Unicode NFKD, 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 optional display_word -> score mapping (or empty).
  • upsert(word: str, score: int) -> None: Insert word or overwrite its integer score if already present. Raise ValueError if normalize(word) is empty.
  • delete(word: str) -> bool: Remove word and return True if present, or False if absent.
  • suggest(prefix: str) -> List[str]: Return up to 5 (TOP_K) display words whose normalize(word) starts with normalize(prefix), ranked in Entry order. Whenever fewer than 5 exact-prefix matches exist, keep all exact matches first and fill the remaining slots (up to 5 total, 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) of normalize(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 after after (or from the start when after is None) in Entry order. next_cursor is the last returned word's Entry when more exact matches remain, or None when the page reaches the end. Raise ValueError if size < 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,000 UTF-8 words, 5,000 QPS, p99 latency < 20 ms, memory <= 300 MB, and ~1,000 concurrent upsert/delete updates per second.
  • Scores are signed integers (higher means more popular); TOP_K = 5.
  • Empty prefix "" matches every stored word in Entry order.
  • upsert raises ValueError if normalize(word) == ""; page raises ValueError if size < 1.
  • Readers (suggest, page) must be safe to run concurrently alongside upsert and delete.

Step-by-step walkthrough

  1. 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 tilde U+0303 are 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), and str.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 score first, then alphabetical normalized_key, then alphabetical display_word (to break ties cleanly when both "Piñata" and "pinata" exist in the catalog). Storing each word as the tuple Entry = (-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 5 words start with normalize(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) from normalize(prefix).
    • Pagination: page(prefix, after, size) steps through exact-prefix matches in the same Entry order using after as a cursor, returning (words, next_cursor) where next_cursor is None on the final page.
  2. Why naive approaches fail—and how 5M words fit in 300 MB

    Scanning 5,000,000 words on every keystroke at 5,000 queries per second requires 2.5 * 10^10 prefix checks per second—far too slow for < 20 ms p99 latency. Compare the four candidate structures under our 300 MB RAM ceiling:

    • Ternary Search Tree (TST): stores one node per character with three child pointers (left, equal, right). Across 5M words, tens of millions of pointer-heavy nodes exceed 300 MB before 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,000 live writes/sec without expensive graph splits.
    • Compressed (radix) trie: merges single-child chains so 5M words need at most 2n = 10M nodes. However, storing 5 int32 IDs (20 B) plus edge labels and child maps on all 10M nodes still pushes right past 300 MB.
    • Sorted arrays + binary search: zero pointer overhead and ceil(log2(5,000,000)) = 23 comparisons 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 is O(n).

    The production design combines sorted flat arrays for a compact Base with a live copy-on-write Trie for a small Delta:

    1. Compact Base (~140 MB, rebuilt every ~5 minutes by shard): stores all 5M normalized keys in one contiguous byte array plus int32 offsets and int32 scores, and caches top-8 IDs in a hash table only for heavy prefixes—prefixes matching more than T = 256 words. Light prefixes (<= 256 matches) just scan their tiny contiguous slice in microseconds! Because prefixes of length L have disjoint ranges, fewer than 5,000,000 / 256 ≈ 19,531 prefixes at each length can be heavy (< 625,000 across lengths 1..32). Caching 8 instead of 5 absorbs deletions between rebuilds.
    2. Live Delta (~30 MB in C++/Rust): a copy-on-write trie holding up to 300,000 writes (5 min * 1,000 writes/s) plus a tombstone set of deleted/rescored base IDs. Queries merge Base + Delta in Entry order, and background workers merge Delta into 1/16th of the Base at a time so temporary memory stays well below 300 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 our Autocomplete class below implements the self-contained copy-on-write trie engine directly (used as the Delta layer at 5M scale, or the entire index for in-memory catalogs).

  3. 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 suggest run in O(|prefix|) time whenever at least 5 exact matches exist, every _Node stores top: the best 5 Entry tuples anywhere in its subtree. Crucially, recomputing node.top never scans the whole subtree—because each child already caches its own top 5, node.top is simply the top 5 among node.words and child.top for 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]
    
  4. Lock-free concurrent reads via copy-on-write updates

    If a writer mutates node.children or node.top in place while 5,000 queries/sec walk the trie, a reader can see half-updated lists or RuntimeError: 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 _Node is reachable from self._root, it is never modified again. When upsert("awl", 10) runs: 1. Acquire self._write_lock (writers serialize against other writers so neither overwrites the other's update). 2. Record the len(key) + 1 existing nodes along "root -> a -> w -> l". 3. Rebuild only those len(key) + 1 nodes from bottom to top, recomputing top at each copied ancestor and dropping any non-root node left with zero words and zero children on delete. Every untouched branch ("am...", "b...") is shared by pointer with the old root! 4. Assign self._root = updated_child in 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._root once 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 True
    
  5. Edit-distance-1 backfill with trie search

    When suggest(prefix) finds fewer than 5 exact matches, we need words that start with some string q at Levenshtein edit distance 1 from key = normalize(prefix). Instead of generating every possible string over the whole Unicode alphabet, _fuzzy_nodes walks existing trie edges with a 1-edit budget (node, index, edited):

    • No edit (edited unchanged): follow node.children[key[index]] and advance index + 1.
    • Deletion from key (!edited -> True): skip key[index] while staying at node (index + 1). Example: "cart" -> "cat".
    • Insertion into key (!edited -> True): follow any child (ch, child) without advancing index. Example: "cat" -> "chat".
    • Substitution (!edited -> True): follow any child (ch, child) with ch != key[index] and advance index + 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
    
  6. 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). Because node.top[0] is the smallest (best) Entry anywhere inside node's subtree, no descendant of node can beat node.top[0]. Whenever we pop an item: - If it holds a _Node, we push all of node.words (marked with None instead of a _Node) and push each child keyed by child.top[0]. - If it holds None, that Entry is 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_ids ensures no trie node is ever expanded twice, and counter breaks ties so heapq never tries to compare two _Node instances.

    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 += 1
    
  7. Assemble 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 = 9 in 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 passing after = last_entry_on_previous_page ((-5, "latch", "latch")) and keeping only entries strictly greater than after (entry > after). Fetching size + 1 entries 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), None
    
  8. Stress-testing strategy and production failure mitigations

    Stress-testing strategy - Differential fuzzing: generate random mixes of accented/uppercase/hyphenated upserts, deletes, suggest, and page calls against a slow brute-force oracle that computes min(levenshtein(p, key[:j])) over every word (implemented in tests.py). - Concurrency linearizability tests: run 16 reader threads continuously calling suggest and page while 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) at 5,000 QPS + 1,000 writes/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 64 characters, reject malformed UTF-8 at the API gateway, cap pagination depth (for example, 10 pages), and enforce a step budget on _fuzzy_nodes / _ranked so pathological queries gracefully return partial exact matches rather than breaching the 20 ms SLA. - 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.

  9. 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 >= 5 exact matches exist) — O(P + K) time: We normalize the prefix and follow P dictionary lookups down the trie in O(P) time, then copy K = 5 pre-sorted entries from exact_node.top in O(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_nodes visits at most P + 1 unedited prefix positions, branches into at most 2B + 1 single-edit states at each position, and follows at most P exact characters afterward (O(B * P^2)). Then _ranked needs at most K distinct words; because every node is keyed by its subtree's best word (node.top[0]) and expanded_node_ids expands each trie node at most once, at most F duplicate start pops plus K * D ancestor nodes are expanded, each pushing up to B + W items onto a heap of size H.
  • page (returning size items after S skipped items) — O(P + (S + size) * D * (B + W) * log H) time: Walking to the prefix node takes O(P), and best-first enumeration expands only ancestors of the S + size + 1 highest-ranked exact matches rather than sorting the entire subtree.
  • upsert and delete — O(L * (W + B * K) * log(W + B * K)) time: Copy-on-write copies L + 1 nodes along the root-to-key path, and at each copied node sorts at most W + B * K candidate entries to rebuild its top list of length K.
  • Space — O(total characters across distinct prefixes * K) for the trie (and ~170 MB in the two-tier Base + Delta architecture for 5M words): Each trie node stores child references plus up to K = 5 tuple references, and each write allocates only L + 1 copied nodes while sharing all off-path subtrees; at 5M-word production scale, flat sorted arrays + heavy-prefix (> 256) top-8 caches (~140 MB) plus the bounded 300k-entry Delta trie (~30 MB) stay comfortably inside the 300 MB RAM limit.

Edge cases

  • Empty prefix (""): normalizes to "", returning self._root.top—the global top 5 across all stored words (or [] when the dictionary is empty).
  • Single-character prefix with < 5 matches (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"): upsert rejects them with ValueError so phantom empty keys never pollute the root, while delete safely returns False.
  • Multiple display spellings sharing one key ("Piñata" and "pinata"): stored side by side in node.words keyed by display string, with Entry = (-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), and casefold() 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, while depth == 0 is preserved so self._root is always a valid _Node.
  • Very long shared prefixes (e.g. 300 'x' characters): an uncompressed trie walks 300 nodes and _fuzzy_nodes takes O(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 filtering not unicodedata.combining(ch) removes nothing and "pinata" fails to match "piñata".
  • Mutating children, words, or top in 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.top or with OFFSET: node.top only caches 5 items, and integer offsets repeat or skip suggestions when concurrent upsert/delete calls shift rankings above the page boundary; use lazy best-first _ranked with 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", and exact_set must filter exact words out of _ranked(fuzzy_starts).
  • Pushing (entry, node) directly onto heapq without an integer tie-breaker: if two sibling subtrees somehow shared an identical tuple prefix or during custom extensions, Python would attempt node1 < node2 and raise TypeError: '<' 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, but 5,000,000 words average 3+ unique prefixes per word (15M+ map entries), blowing past 300 MB on keys, hash buckets, and 5-ID arrays alone—plus every score update must touch L hash 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,000 writes/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), exceeding 300 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_nodes whenever not edited and index + 1 < len(key) and key[index] != key[index + 1]: step from node along key[index + 1] to mid_node, then along key[index] to swapped_node, and push (swapped_node, index + 2, True). Because swapped_node is an ordinary trie node, _ranked, deduplication, and Entry tie-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 >= 3 routes directly to a single shard for exact matches, while keeping a tiny replicated cache of global top-5 lists for prefixes of length 0..2 on 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 50 candidates lazily using _ranked (increasing node.top or running a bounded 50-pop best-first walk), and re-score just those 50 candidates in < 1 ms using 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

Similar questions

More Etsy interview questions

All 1 Etsy questions →