Tries (Prefix Trees)

A tree keyed by characters — O(L) insert and lookup, and instant prefix queries for autocomplete and dictionaries.

Intermediate 2 min readLesson 11 of 16 Interview Q&A

A trie (pronounced "try", from retrieval) stores a set of strings as a tree where each edge is a character. Words that share a prefix share a path. Lookup cost depends only on the word length L, not on how many words are stored.

ttracgod·
Trie containing "cat", "car", "cart", "dog". Green nodes mark the end of a word.

Operations

OperationTimeNotes
Insert wordO(L)Create missing nodes along the path
Search wordO(L)Path must exist and end at an end-of-word node
Starts-with prefixO(P)Path just has to exist
List all words with a prefixO(P + output)DFS below the prefix node

Compared with a hash set, a trie answers prefix questions natively and lists keys in sorted order, at the cost of more memory.

class Trie {
    private static class Node {
        Node[] next = new Node[26];   // or Map<Character, Node> for large alphabets
        boolean end;
    }
    private final Node root = new Node();

    public void insert(String word) {
        Node n = root;
        for (char c : word.toCharArray()) {
            int i = c - 'a';
            if (n.next[i] == null) n.next[i] = new Node();
            n = n.next[i];
        }
        n.end = true;
    }

    public boolean search(String word) {
        Node n = walk(word);
        return n != null && n.end;
    }

    public boolean startsWith(String prefix) {
        return walk(prefix) != null;
    }

    private Node walk(String s) {
        Node n = root;
        for (char c : s.toCharArray()) {
            n = n.next[c - 'a'];
            if (n == null) return null;
        }
        return n;
    }
}

Memory trade-offs

  • Array children (Node[26]): fastest, but every node reserves 26 pointers even if it uses one.
  • Map children: compact for sparse or large alphabets (Unicode), slightly slower.
  • Radix / Patricia tree: compresses chains of single-child nodes into one edge labelled with a whole substring. Used in IP routing tables, Linux's page cache, and Ethereum's state tree.

Where tries are used

  • Autocomplete and spell checking — walk to the prefix, DFS for suggestions (often ranked by frequency stored in nodes).
  • IP routing — longest-prefix match over binary address bits.
  • Word games / Boggle / Word Search II — prune grid DFS the moment a path is not a prefix of any word.
  • XOR maximisation — a binary trie over bits finds the number maximising x XOR y in O(32). See Bitwise XOR.
Key takeaways
  • A trie stores strings as paths of characters; shared prefixes share nodes.
  • Insert, search and prefix queries cost O(length), independent of the number of words.
  • Mark word ends explicitly — a prefix is not a word.
  • Radix trees compress single-child chains to save memory.
Interview questions
QImplement autocomplete returning the top 3 suggestions for each typed prefix.medium

Build a trie; at each node store the top-3 words (by frequency or lexicographically) passing through it, updated on insert. Each keystroke moves one node down and returns the stored list in O(1). Alternatively, sort the words and binary-search the prefix range.

QTrie vs hash set for a dictionary — when is a trie better?easy

When you need prefix queries, sorted iteration, or longest-prefix matching. A hash set is simpler and usually faster for exact membership only.