Problem overview
A trie, or prefix tree, stores words letter by letter. Each node stands for a prefix, and each child adds one more letter to it. Words that begin the same way share the same path from the root, so asking about a word takes time that depends only on its length.
The lesson builds two structs. Trie has three functions: insert(&mut self, word: String) adds a word, search(&self, word: String) -> bool tells whether exactly that word was inserted, and starts_with(&self, prefix: String) -> bool tells whether some inserted word begins with the prefix. A word counts as a prefix of itself. The nodes are a second struct, TrieNode.
After insert("apple"), search("apple") is true, search("app") is false, and starts_with("app") is true. After insert("app"), search("app") is true as well. With car and cart inserted, starts_with("ca") is true and search("ca") is false, because ca itself was never inserted.
Approach: one node per prefix
Storing the words in a list and comparing against each one would cost time proportional to the number of words. A trie goes straight down the word's path instead, so each operation takes O(L) for a word or prefix of length L, however many words are stored.
Each node needs to know two things:
- Its children: a map from the next letter to the child node for that letter.
- Whether a word ends here: a boolean flag,
is_end.
The flag matters because paths are shared. After inserting apple, the nodes for app and apple both exist, but only the node for apple ends a word. That is exactly the difference between search and starts_with. Both walk the same path down the letters. When a letter has no child, both answer false. When the whole path exists, search answers with the end flag, and starts_with answers true, because every node lies on the path of some inserted word.
The root stands for the empty prefix. An empty trie is a root with no children.
Step by step
- Declare
TrieNode. It gets a fieldchildren: HashMap<char, TrieNode>and a fieldis_end: bool. A struct can hold a map of its own type, because theHashMapkeeps its values on the heap and the struct has a fixed size. - Write
TrieNode::new. It returns a node withHashMap::new()as the children andfalseasis_end. - Declare
Trie. Its only field isroot: TrieNode, andTrie::newreturns a trie withTrieNode::new()as the root. - Start
insertat the root.let mut node = &mut self.root;is a mutable reference, so the walk can add children and set the flag, andnodeitself ismutso it can move to other nodes. - Walk the letters. A
forloop overword.chars()goes one level down per letter. - Create the missing child. If
node.childrenhas no keyc, checked withcontains_key(&c), insert a freshTrieNode::new()underc. - Step down.
node = node.children.get_mut(&c).unwrap();moves to the child.get_mutreturns anOption, andunwrap()is safe because the child exists now. - Mark the end. After the loop,
node.is_end = true;makes the word count as inserted, and not only as the beginning of a longer one. searchfollows the same path without creating anything.let mut node = &self.root;is a shared reference, because reading changes nothing. If a letter has no child, returnfalse. Otherwise move down withnode = &node.children[&c];, which is safe because the check above made sure the key exists.- End
search. Returnnode.is_endas the last expression. Reaching the node isn't enough, because the path may exist only as part of a longer word. starts_withis the same walk. It differs only at the end: after the loop it returnstrue.
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 Trie {
root: TrieNode,
}
impl Trie {
fn new() -> Trie {
Trie { root: TrieNode::new() }
}
fn insert(&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 mut node = &self.root;
for c in word.chars() {
if !node.children.contains_key(&c) {
return false;
}
node = &node.children[&c];
}
node.is_end
}
fn starts_with(&self, prefix: String) -> bool {
let mut node = &self.root;
for c in prefix.chars() {
if !node.children.contains_key(&c) {
return false;
}
node = &node.children[&c];
}
true
}
}
The Rust details worth a closer look:
- Moving a reference down the tree.
nodeis a reference, and reassigning it walks one level down without copying any node. Ininsertthe reference is&mut, so it is the only live way to reach that part of the trie, and the borrow checker accepts the reassignment because the old borrow ends whennodetakes the new value. Insearchandstarts_withit is a shared&, and the functions take&self, so they can't change the trie by accident. contains_keytakes a reference. The key type ischar, so the calls pass&c. The same goes for indexing a map:node.children[&c]returns the value for that key, and panics if the key is missing, which is why the code checks first.- Characters, not bytes.
word.chars()yieldscharvalues, which are full Unicode characters. The lesson's words use lowercase lettersatoz, so every character is one byte anyway. - The entry API as an alternative.
node = node.children.entry(c).or_insert_with(TrieNode::new);does the check, the insert and the step down in one line, and gives the same result. The lesson spells the steps out, which makes each one visible. - Insert order of the walk. The new child is created before stepping into it, so
get_mut(&c).unwrap()never sees a missing key. - Last expressions.
node.is_endandtruehave no semicolon, so they are the values returned after the loops.
Complexity
Time: O(L) per operation, where L is the length of the word or prefix. Each letter costs one map lookup, and one insertion at most, which are constant on average for a HashMap.
Space: O(total letters) for the trie. The number of nodes is at most the total length of all inserted words, plus the root, and shared prefixes make it smaller. Inserting car and cart creates 4 nodes below the root, not 7. A search or a prefix check uses O(1) extra space.
Edge cases and common mistakes
- A prefix is not a word. After inserting
apple,search("app")isfalse. Returningtrueat the end ofsearchinstead ofnode.is_endwould make ittrue. - A word is a prefix of itself. After inserting
dog,starts_with("dog")istrue. - Inserting twice. Inserting
doga second time finds every child already there and sets the flag totrueagain, so nothing changes. - A word longer than the stored one. With only
doginserted,search("dogs")andstarts_with("dogs")are bothfalse: the path stops afterg. - Forgetting the end flag on the new word. If
insert("app")is called afterinsert("apple")and the loop only creates missing children,search("app")still returnsfalseunlessis_endis set. - The empty prefix. The loop doesn't run, so
starts_withreturnstrueeven for an empty trie. An empty word searched in an empty trie givesfalse, because the root's flag isfalse. The lesson's words have at least one letter, so neither case occurs.
Testing
- Insert
apple, thensearch("apple"),search("app"),starts_with("app"), insertapp,search("app"):true false true true. - Insert
carandcart, thenstarts_with("ca"),search("ca"),starts_with("cat"),search("cart"):true false false true. - Insert
dogtwice, thensearch("dog"),starts_with("dog"),search("do"),starts_with("dogs"),search("dogs"):true true false false false.
