Tries · Lesson

Tries, explained: prefix trees for words, autocomplete and XOR

Learn the trie (prefix tree): insert, search and starts-with, autocomplete, word search on a grid and the bitwise trie, with code in Java, Python, C++ and JS.

3 patterns · 9 problems · Java, Python, C++ and JavaScript

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

What a trie is

A trie (say "try", also called a prefix tree) stores words one character per level. The root is the empty string, each edge adds one letter, and words that share a prefix share the same path: "car", "cart" and "care" all walk through c → a → r.

Each node also needs a flag: does a word end here? Without it you cannot tell the word "car" from the prefix of "cart". Looking up a word or a prefix of length L takes L steps, no matter how many words the trie holds.

When a trie beats a hash set

A hash set answers "is this exact word here?" just as fast. A trie wins when the question is about prefixes:

  • Starts-with queries: every word below a node shares its prefix, so autocomplete is a walk plus a small DFS.
  • Searching many words at once: walking a grid or a string, you can stop the moment no word continues the current path.
  • Wildcards: a . that matches any letter just tries every child at that level.
  • Bits instead of letters: store numbers bit by bit, highest first, and you can find the number with the largest XOR greedily.

What it costs

OperationTimeSpace
Insert a word of length LO(L)O(L) new nodes at most
Search a word or check a prefixO(L)O(1)
Build from words with N letters in totalO(N)O(N · alphabet) with child arrays
Max XOR of a number with a bitwise trieO(B) for B bitsO(n · B) for n numbers
Same prefix queries on a sorted list (binary search)O(L log n)O(1) extra

Built into your language

Library calls
// no trie in the standard library: write a node with 26 children (or a HashMap)
"apple".startsWith("app");                 // true

// a sorted set can answer prefix questions too
TreeSet<String> words = new TreeSet<>(List.of("app", "apple", "bat"));
words.ceiling("ap");                       // "app": the first word >= the prefix
words.subSet("ap", "ap" + Character.MAX_VALUE);   // [app, apple]: every word with the prefix

Mistakes everyone makes

  • Confusing "the prefix exists" with "the word exists": search must check the end flag.
  • Using a fixed 26-child array when the input has uppercase letters, digits or /: use a map.
  • Forgetting to decrement counts on erase, so prefix counts drift.
  • Building a new string at every step of a DFS: pass the node along, or store the whole word in its end node.

The 3 patterns, in order

Each one: the idea and template, its variations with a worked example, then problems for you to solve.

  1. 1 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
  2. 2 Trie + backtracking: find many words at once Put all the words in a trie, then backtrack over the grid while walking the trie at the same time. The moment the current path is not a prefix of any word, stop: that pruning is what makes it fast. 1 variation · 1 problem
  3. 3 Bitwise trie: the largest XOR, bit by bit Store each number as a path of bits from the highest to the lowest, so every node has at most two children. To get the largest XOR with x, walk down and take the opposite bit whenever it exists. 1 variation · 1 problem