synopsis · Trees & graphs · chapter 25
Tries
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A tree of characters: each edge is a letter, each node a prefix, and an
isEndflag marks where a stored word ends. Shared beginnings are stored once. - use it when
Prefix questions over one set of strings: startsWith, autocomplete, shortest root, many words on one board, wildcard search — and max XOR with a binary trie.
- template
for (char ch : w.toCharArray()) { int i = ch - 'a'; if (cur.children[i] == null) cur.children[i] = new Node(); cur = cur.children[i]; }thencur.isEnd = true; - cost
insert / search / startsWith = O(L) for an L-letter word, whatever the number of words. Memory: up to one node per stored letter, 26 slots each with
Node[26]. - trap
searchmust checkisEndat the last node — otherwise "app" is "found" after inserting only "apple". - trap
ch - 'a'assumes lowercase a–z. Uppercase, digits or spaces give an index outside 0..25 → ArrayIndexOutOfBoundsException. Use a HashMap per node. - pro tip
Many words, one board? Build one trie, run one DFS that follows it, prune when no word continues. Store the whole word on its end node.
- pro tip
Max XOR: insert bits 30 → 0 into a binary trie; at each bit take the opposite child if it exists. A higher bit beats all lower bits together.
- pro tip
Top-k suggestions fast: insert words in sorted order and keep the first k on every node — each typed letter is then O(1).
Shaky on a card? Open the chapter or flip its recall cards.