Algorithms

Trie (prefix tree)

The user entered “cat”. How can we suggest “catfish” and “catalog”? A trie lets all three words share one branch. Follow “c”, “a”, and “t” once, then explore the continuations.

A double outline marks a complete word. Tap a node to see its full prefix.

Use Left and Right to select a node, Enter to show its prefix, and Escape to close the tooltip.

∅ · Start at the empty root.

Video walkthrough

Previous episode — Levenshtein distance

One path for a shared prefix

Each node except the root is labeled with one symbol. Moving from the parent to that node appends the symbol to the prefix. Reading the labels along the path from the root gives the prefix. A separate marker means that this prefix is also a complete dictionary word. The node for “cat” can end a word and have descendants.

Finding suggestions

Follow each symbol of the query. A missing edge means there are no suggestions. Otherwise, collect words in the current subtree, including a word at the current node. The empty prefix matches the entire dictionary. Finding a prefix takes O(p) transitions for p query symbols under the usual Map lookup assumption. Exploring the subtree takes time proportional to the nodes visited and the output size.

Handling a typo

In one-edit mode, the demo computes a Levenshtein row for each prefix. To visit a child, append one symbol and compute the next row. Both “catfish” and “catalog” reuse the “cat” row. The last number is the distance from the current prefix to the whole query. If the entire row exceeds one, skip the branch: appending a symbol cannot lower the row minimum.

Tree size and query cost

The number of nodes is at most the total length of the words plus the root. Shared prefixes reduce it. Typo search does O(p + 1) work per visited node. The demo lowercases its input and compares Unicode code points after NFC normalization. Spaces within words are outside its input format.

A trie in JavaScript

Each node stores outgoing edges in a Map. The function returns every word starting with the requested prefix.

function autocomplete(words, prefix) {
    const normalize = s => s.normalize('NFC').toLowerCase().normalize('NFC');
    const node = () => ({ edges: new Map(), word: null });
    const root = node();
    for (const input of words) {
        const word = normalize(input);
        let current = root;
        for (const symbol of word) {
            if (!current.edges.has(symbol)) current.edges.set(symbol, node());
            current = current.edges.get(symbol);
        }
        current.word = word;
    }
    let current = root;
    for (const symbol of normalize(prefix)) {
        current = current.edges.get(symbol);
        if (!current) return [];
    }
    const matches = [];
    function visit(entry) {
        if (entry.word !== null) matches.push(entry.word);
        for (const child of entry.edges.values()) visit(child);
    }
    visit(current);
    return matches;
}