Command Palette

Search for a command to run...

Module 19

Trie

A tree of characters: insert and search in O(word length), prefix counts, autocomplete, wildcard search, word grids and the binary trie for XOR.

Intermediate 4 lessons 7 problems ~45 min of lessons

A trie (say "try", from the word "retrieval") stores strings by sharing their prefixes: "car", "cat" and "cart" all walk through the same c → a nodes. Looking up a word or a prefix costs O(length of the word), no matter how many words are stored, and prefix questions that are awkward with a hash map become a single walk.

This module builds the trie, adds prefix counts for autocomplete, combines it with DFS for wildcards and word grids, and finishes with the binary trie, which stores numbers bit by bit to answer maximum-XOR questions.

Best after: Binary Trees, Strings

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The trie itself: insert, search and startsWith.

  2. Wildcard search: DFS over every child at a ..

  3. Search many words at once by walking a trie alongside a grid DFS.

  4. Shortest-prefix lookup: stop at the first end-of-word node on the path.

  5. DFS over a trie, moving only through nodes that end words.

  6. Autocomplete: up to three sorted suggestions per typed prefix.

  7. The binary trie: greedy choice of the opposite bit from the top down.