Tries · Pattern 1 of 3

Trie basics: insert, search, prefixes and autocomplete

Walk the word letter by letter, creating missing children on insert and stopping at a missing child on search. Counts in the nodes, wildcards and autocomplete are small additions to the same walk.

4 variations · 7 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Insert words and ask whether a word or a prefix exists
  • How many words start with a prefix, with inserts and erases
  • Suggestions after each typed letter
  • A . that matches any letter

The template

Basics
class Trie {
    class Node { Node[] next = new Node[26]; boolean end; }
    Node root = new Node();

    void insert(String word) {
        Node cur = root;
        for (char c : word.toCharArray()) {
            if (cur.next[c - 'a'] == null) cur.next[c - 'a'] = new Node();   // create the path
            cur = cur.next[c - 'a'];
        }
        cur.end = true;                             // a word ends here
    }
    Node walk(String s) {                           // the node for s, or null
        Node cur = root;
        for (char c : s.toCharArray()) {
            cur = cur.next[c - 'a'];
            if (cur == null) return null;
        }
        return cur;
    }
    boolean search(String word) { Node n = walk(word); return n != null && n.end; }
    boolean startsWith(String prefix) { return walk(prefix) != null; }
}

The variations

  1. 1Build a trie

    Insert creates missing children; search and starts-with walk and stop at a missing child. Add two counters per node (words passing through, words ending here) to count prefixes and support erase. The longest common prefix of two numbers is how far the second walks in a trie of the first list's digits.

  2. 2Wildcard search with DFS

    Search recursively with the node and the position in the word. A letter follows one child; a . tries every child and succeeds if any branch does. At the end of the word, check the end flag.

  3. 3Autocomplete

    Walk the typed prefix once, keeping the node as each letter is added. The suggestions are the first words below that node: visit children in letter order, or keep the top few words in each node. Ranking by how often a sentence was typed is the same walk with counts.

  4. 4A trie of path parts

    Split a path like /a/b/c on / and treat each name as one "letter", with a map of children per node. A file is a node that also holds content; listing a directory is its children in sorted order.

Mistakes to avoid

  • Returning true from search for a word that is only a prefix: "app" after inserting only "apple".
  • Wildcard search that returns after trying the first child: try every child and return true if any succeeds.
  • Autocomplete that collects every word below the node and then sorts: visit children in letter order and stop after k words.
Next: Trie + backtracking: find many words at once →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.