Python coding

Typeahead suggestions

A search box suggests words as you type. Given a dictionary words and the string typed, return one list per character typed: after the first i characters, the up to 3 alphabetically smallest words that start with typed[:i], in alphabetical order. A word repeated in words is suggested once, and a word equal to the prefix counts as a match.

Words and typed use lowercase a–z; 1 ≤ len(typed) ≤ 20.

  • suggestions(["apple","apply","ape","april","bat","apt"], "apr") → [["ape","apple","apply"],["ape","apple","apply"],["april"]]
  • suggestions(["tea","ten","toe"], "tx") → [["tea","ten","toe"],[]]
  • suggestions(["go","go","gone","good"], "go") → [["go","gone","good"],["go","gone","good"]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Put the words in a trie: every word with a given prefix lives below the node that prefix reaches, and each keystroke moves one node down.

Hint 2

Insert the distinct words in sorted order and keep, on each node, the first 3 words that pass through it: those are its 3 smallest.

Hint 3

Once a character has no child, no longer prefix can match either: return empty lists for the rest of typed.

Solution and why it works
pythonO(L·n log n + t), n words, L = longest word, t = len(typed) · O(n·L) for the trie
def suggestions(words: list[str], typed: str) -> list[list[str]]:
    root = {"kids": {}, "top": []}
    for w in sorted(set(words)):
        node = root
        for ch in w:
            node = node["kids"].setdefault(ch, {"kids": {}, "top": []})
            if len(node["top"]) < 3:
                node["top"].append(w)
    res, node = [], root
    for ch in typed:
        node = node["kids"].get(ch) if node is not None else None
        res.append(node["top"] if node is not None else [])
    return res

Inserting the distinct words in alphabetical order means the first 3 to pass through a node are the 3 smallest with that prefix, so each node stores its own answer and every keystroke costs one step down the trie, not a scan of the dictionary. The trap is the dead end: after a character with no child, keep returning empty lists instead of reading a missing node or restarting from the root.