Problem overview
The lesson builds a WordDictionary that stores words and finds them again, where the word being searched for may contain dots. A dot matches any one letter. It has two public functions: add_word(&mut self, word: String) and search(&self, word: String) -> bool. A search is true when some added word has the same length and, at every position, the same letter, except that a dot at a position accepts any letter. The nodes are a TrieNode struct, and the recursive work is done by the helper search_from(node: &TrieNode, word: &[char], i: usize) -> bool.
With bad, dad and mad added, search("pad") is false, search("bad") is true, search(".ad") is true (it matches all three words), and search("b..") is true. A dot stands for exactly one letter, never for none: with only at added, search("at.") is false and search(".t") is true. And a search must match a whole word, so search("a") is false there.
Approach: a trie, and a search that branches at dots
The words are stored in a trie, as in a plain prefix tree: one node per prefix, a map from the next letter to the child node, and a flag, is_end, on the node where an added word ends. Adding a word follows its letters from the root, creating missing nodes, and takes O(L) for a word of length L.
Searching a word without dots is the same walk: follow the letters, and the answer is the end flag of the node you reach. A dot changes things. At a dot the search doesn't know which child to take, so it tries all of them, and it is enough that one of them leads to a match. That makes the search a recursion: search_from(node, word, i) asks whether the rest of word, from index i on, matches a path that starts at node.
- The end of the word (
i == word.len()): every character was matched, so the answer is whether a word ends exactly at this node. - A dot: try every child with
i + 1, and answertrueas soon as one returnstrue. - A letter: if the node has no such child, answer
false. Otherwise recurse into that one child withi + 1.
A search without dots takes O(L), since a letter has only one way to go. At a dot, the search may try every child of the node, which is why the lesson limits a search word to at most 2 dots. The branching then happens at most twice, at up to 26 children each.
Step by step
- Declare
TrieNode. Its fields arechildren: HashMap<char, TrieNode>andis_end: bool. A struct can hold a map of its own type because theHashMapkeeps its values on the heap. - Write
TrieNode::newwith an empty map andis_endset tofalse. - Declare
WordDictionary. It has one field,root: TrieNode, the node of the empty prefix.WordDictionary::newreturns one withTrieNode::new()as the root. add_wordstarts withlet mut node = &mut self.root;and loops overword.chars(). For each letter it inserts a newTrieNodeif the key is missing (contains_key(&c)takes a reference), and moves down withget_mut(&c).unwrap(). After the loop it setsnode.is_end = true.- Collect the characters in
search.let chars: Vec<char> = word.chars().collect();, because aStringcan't be indexed by position, and the helper readsword[i]. - Delegate to the helper.
searchreturnsSelf::search_from(&self.root, &chars, 0). The helper has noself, so it is called throughSelf::, and&charslends the vector as the slice&[char]that the helper expects. - The base case. In
search_from, ifi == word.len(), returnnode.is_end. - Read the current character:
let c = word[i];. - Handle a dot. If
c == '.', loop overnode.children.values(), the child nodes. IfSelf::search_from(child, word, i + 1)istrue, returntrueat once. If the loop ends, no child led to a match, so returnfalse. - Handle a letter. If
node.childrenhas no keyc, returnfalse. - Follow the letter. Return
Self::search_from(&node.children[&c], word, i + 1)as the last expression: one recursive call moves one level down.
The solution in Rust
use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, TrieNode>,
is_end: bool,
}
impl TrieNode {
fn new() -> TrieNode {
TrieNode { children: HashMap::new(), is_end: false }
}
}
struct WordDictionary {
root: TrieNode,
}
impl WordDictionary {
fn new() -> WordDictionary {
WordDictionary { root: TrieNode::new() }
}
fn add_word(&mut self, word: String) {
let mut node = &mut self.root;
for c in word.chars() {
if !node.children.contains_key(&c) {
node.children.insert(c, TrieNode::new());
}
node = node.children.get_mut(&c).unwrap();
}
node.is_end = true;
}
fn search(&self, word: String) -> bool {
let chars: Vec<char> = word.chars().collect();
Self::search_from(&self.root, &chars, 0)
}
fn search_from(node: &TrieNode, word: &[char], i: usize) -> bool {
if i == word.len() {
return node.is_end;
}
let c = word[i];
if c == '.' {
for child in node.children.values() {
if Self::search_from(child, word, i + 1) {
return true;
}
}
return false;
}
if !node.children.contains_key(&c) {
return false;
}
Self::search_from(&node.children[&c], word, i + 1)
}
}
The Rust details worth a closer look:
&[char]andVec<char>. A slice borrows a run of elements without owning them. Passing&chars, a reference to aVec<char>, works where&[char]is expected, because Rust converts the reference automatically. The recursion passes the same slice down and changes only the indexi, so no copy is made at any level.- Why not index the string? A
Stringis UTF-8 bytes, soword[i]doesn't compile on it. Turning it into a vector ofchargives constant-time indexing by character. values()iterates over a map's values, here shared references to the child nodes, which is whatsearch_fromtakes. The order is unspecified for aHashMap, which doesn't matter: the search wants any one match.- Early
returninside a loop.return trueleaves the whole function, not only the loop, so the first matching child ends the search.return falseafter the loop runs only if no child matched. - Shared references in the search.
searchtakes&selfand the helper takes&TrieNode, so searching never changes the dictionary, and the recursion can borrow every child at once. - Dots are only meaningful in a search.
add_wordtreats every character as a letter. The lesson guarantees added words have only lowercase letters. - Last expression. The final call in
search_fromhas no semicolon, so its value is the function's result.
Complexity
add_word: O(L) time, with one map lookup and at most one insertion per letter.
search: O(L) without dots. With dots, a dot may branch into every child, up to 26. With at most 2 dots, the branching happens at most twice, so the work stays a constant factor times L. A general pattern with many dots could visit a large part of the trie.
Space: O(total letters) for the nodes, because shared prefixes share nodes. The search itself uses O(L) for the character vector and the recursion stack.
Edge cases and common mistakes
- A dot needs exactly one letter. With
atadded,search("at.")isfalse, because aftertthere is no child to match the dot.search(".")isfalsetoo, because a one-letter word was never added. - A prefix isn't a match.
search("a")with onlyatadded isfalse. The base case checksis_end, not just that the path exists. - Different lengths. With
aandabadded,search("..")istrueandsearch(".a")isfalse. Length is decided by the end flag at the end of the search word. - A dot at the start, middle or end.
search(".ad")andsearch("b..")both matchbad. The code treats a dot the same way at every position. - Returning
falsetoo early at a dot. A failed child must not end the search, because a later child may still match. Only the loop's end, after every child has failed, returnsfalse. - Returning
truefor an empty dictionary. Without words, every search fails: the root has no children, so any letter or dot reachesfalse. - Forgetting the base case. Without the check at
i == word.len(),word[i]would run past the end and panic with an index out of bounds.
Testing
- Add
bad,dad,mad, then searchpad,bad,.ad,b..:false true true true. - Add
aandab, then search.,a.,.b,.a,..,b:true true true false true false. - Add
at, then searcha,at.,.t,a..,.:false false true false false. - Add
cat,car,cab, then searchca.,c.t,...,..,....:true true true false false. - Search
aand.in an empty dictionary:false false.
