Trie Pattern

Prefix problems — autocomplete, word search on a board, replace words, and XOR maximisation with a binary trie.

Intermediate 2 min readLesson 16 of 25

Use a trie when a problem asks about prefixes across many strings, or when you need to search many words at once. Each node is a prefix; walking down the trie runs the search for every word with that prefix at the same time.

tcatrcaracgdogod·
Trie for cat, car, dog. Green nodes end a word.
When to use this pattern
  • "Starts with", autocomplete, longest common prefix, word suggestions.
  • Searching a grid or text for many dictionary words at once (Word Search II).
  • Replacing words with their shortest root, or matching wildcard patterns (.).
  • Maximum XOR of pairs: a trie over the bits of the numbers.

Template

class Trie {
    Trie[] next = new Trie[26];
    String word;                     // set on the node that ends a word

    void insert(String w) {
        Trie n = this;
        for (char ch : w.toCharArray()) {
            int i = ch - 'a';
            if (n.next[i] == null) n.next[i] = new Trie();
            n = n.next[i];
        }
        n.word = w;
    }

    boolean startsWith(String p) {
        Trie n = this;
        for (char ch : p.toCharArray()) {
            n = n.next[ch - 'a'];
            if (n == null) return false;
        }
        return true;
    }
}

Word Search II: trie + backtracking

Put every word in a trie, then DFS from each cell, walking the trie in step with the board. Stop as soon as the current path is not a prefix of any word.

List<String> findWords(char[][] b, String[] words) {
    Trie root = new Trie();
    for (String w : words) root.insert(w);
    List<String> res = new ArrayList<>();
    for (int r = 0; r < b.length; r++)
        for (int c = 0; c < b[0].length; c++) dfs(b, r, c, root, res);
    return res;
}

void dfs(char[][] b, int r, int c, Trie n, List<String> res) {
    if (r < 0 || c < 0 || r >= b.length || c >= b[0].length) return;
    char ch = b[r][c];
    if (ch == '#' || n.next[ch - 'a'] == null) return;   // not a prefix → prune
    n = n.next[ch - 'a'];
    if (n.word != null) { res.add(n.word); n.word = null; }  // avoid duplicates
    b[r][c] = '#';
    dfs(b, r + 1, c, n, res); dfs(b, r - 1, c, n, res);
    dfs(b, r, c + 1, n, res); dfs(b, r, c - 1, n, res);
    b[r][c] = ch;                                          // backtrack
}

Binary trie: maximum XOR of two numbers

Insert each number bit by bit, from bit 31 down. For each number, walk the trie greedily choosing the opposite bit whenever it exists. That maximises the XOR from the highest bit down. O(n · 32).

int findMaximumXOR(int[] nums) {
    int[][] t = new int[nums.length * 32 + 1][2];
    int cnt = 1, best = 0;
    for (int x : nums) {
        int n = 0, m = 0, cur = 0;
        for (int b = 31; b >= 0; b--) {                 // insert
            int bit = (x >>> b) & 1;
            if (t[n][bit] == 0) t[n][bit] = cnt++;
            n = t[n][bit];
        }
        for (int b = 31; b >= 0; b--) {                 // query: prefer the opposite bit
            int bit = (x >>> b) & 1;
            if (t[m][bit ^ 1] != 0) { cur |= 1 << b; m = t[m][bit ^ 1]; }
            else m = t[m][bit];
        }
        best = Math.max(best, cur);
    }
    return best;
}
Practice problems
  • Implement Trie (Prefix Tree)medium
  • Longest Common Prefixeasy
  • Design Add and Search Words Data Structure'.' branches to all childrenmedium
  • Replace Wordsstop at the first word endmedium
  • Search Suggestions Systemmedium
  • Maximum XOR of Two Numbers in an Arraybinary triemedium
  • Word Search IIhard
  • Palindrome Pairshard
Key takeaways
  • Prefixes across many strings ⇒ trie.
  • Store the whole word (or an end flag) on the terminal node.
  • Trie + DFS searches many words at once and prunes dead prefixes.
  • A binary trie over bits answers "maximum XOR" greedily from the top bit.
  • Time O(L) per operation; memory up to total characters × alphabet size.