Chapter 12 - Tries
A tree of characters where words share their prefixes. Search time depends on the length of the word, not on the size of the dictionary.
This page is the entry point of chapter 12 of my Rust solutions to the book Coding Interview Patterns. It sums up the pattern in a few lines, then lists the problems of the chapter. As explained on the series page, the detailed explanations of the algorithms are in the book.
The idea
Each node of a trie has one child per possible next character and a flag that marks the end of a word. Inserting or looking up a word walks down one node per character. Since common prefixes are stored once, a trie can prune a search as soon as a prefix leads nowhere, which is what makes Find All Words on a Board fast.
When to reach for it
- Prefix questions: autocomplete, “starts with”.
- Dictionaries with wildcard search.
- Searching many words at once on a grid, combined with backtracking.
In Rust
- Children can be a
HashMap<char, TrieNode>(any alphabet) or[Option<Box<TrieNode>>; 26](lowercase letters). - With
#[derive(Default)]on the node,node.children.entry(c).or_default()walks and creates in one line. - Walk the trie iteratively with a
&mutcursor: it is simpler than a recursive insert in Rust.
Problems in this chapter
- p230 - Design a Trie: Design a Trie (Tries), solved in Rust. Design and implement a trie data structure.
- p235 - Insert and Search Words with Wildcards: Insert and Search Words with Wildcards (Tries), solved in Rust. Design and implement a trie data structure.
- p239 - Find All Words on a Board: Find All Words on a Board (Tries) solved in Rust: find which words of a list can be spelled with adjacent cells of a 2D board of characters.
Other chapters
All the chapters, with every problem, are listed on the series page.