Start learning free

LESSON 220 OF 314 · TRIES

Implement Trie (Prefix Tree) in Rust: HashMap Nodes, O(L) Operations

Practice O(L) Read the full explanation

A trie (pronounced "try"), or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each of its children adds one more letter to that prefix. Words that begin the same way share the same path from the root, so a trie can tell whether a word was added, or whether any added word starts a certain way, in time that depends only on the length of the word asked about. Autocomplete and spell checkers work this way.

Implement the class Trie:

  • Trie() creates an empty trie.
  • insert(word) adds the string word to the trie.
  • search(word) returns true if word was inserted before, and false otherwise.
  • startsWith(prefix) returns true if some inserted word starts with prefix, and false otherwise. A word counts as a prefix of itself.

The input is a list of operations, applied in order to one new trie. The output lists what the search and startsWith calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
    insert("apple")
    search("apple")
    search("app")
    startsWith("app")
    insert("app")
    search("app")
Output: true false true true
Explanation:
"apple" was inserted, so search("apple") is true.
"app" is only the beginning of "apple": search("app") is false, but startsWith("app") is true.
After insert("app"), search("app") is true.

Example 2:

Input:
    insert("car")
    insert("cart")
    startsWith("ca")
    search("ca")
    startsWith("cat")
    search("cart")
Output: true false false true
Explanation: Both words start with "ca", but "ca" itself was never inserted. No word starts with "cat".

Example 3:

Input:
    insert("dog")
    insert("dog")
    search("dog")
    startsWith("dog")
    search("do")
    startsWith("dogs")
    search("dogs")
Output: true true false false false
Explanation: Inserting "dog" a second time changes nothing. "dog" is a prefix of itself, so startsWith("dog") is true. Nothing longer than "dog" was inserted.

 

Constraints:

  • 1 <= word.length, prefix.length <= 30
  • word and prefix consist of lowercase English letters, a to z.
  • At most 105 calls in total are made to insert, search and startsWith.

Note:

Each operation should run in O(L) time, where L is the length of its word or prefix.

STEP 1 OF 20
    Ctrl + Enter to check

    RUST · TRIES

    Implement Trie Prefix Tree in Rust, explained

    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

    1. Declare TrieNode. It gets a field children: HashMap<char, TrieNode> and a field is_end: bool. A struct can hold a map of its own type, because the HashMap keeps its values on the heap and the struct has a fixed size.
    2. Write TrieNode::new. It returns a node with HashMap::new() as the children and false as is_end.
    3. Declare Trie. Its only field is root: TrieNode, and Trie::new returns a trie with TrieNode::new() as the root.
    4. Start insert at the root. let mut node = &mut self.root; is a mutable reference, so the walk can add children and set the flag, and node itself is mut so it can move to other nodes.
    5. Walk the letters. A for loop over word.chars() goes one level down per letter.
    6. Create the missing child. If node.children has no key c, checked with contains_key(&c), insert a fresh TrieNode::new() under c.
    7. Step down. node = node.children.get_mut(&c).unwrap(); moves to the child. get_mut returns an Option, and unwrap() is safe because the child exists now.
    8. 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.
    9. search follows 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, return false. Otherwise move down with node = &node.children[&c];, which is safe because the check above made sure the key exists.
    10. End search. Return node.is_end as the last expression. Reaching the node isn't enough, because the path may exist only as part of a longer word.
    11. starts_with is the same walk. It differs only at the end: after the loop it returns true.

    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. node is a reference, and reassigning it walks one level down without copying any node. In insert the 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 when node takes the new value. In search and starts_with it is a shared &, and the functions take &self, so they can't change the trie by accident.
    • contains_key takes a reference. The key type is char, 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() yields char values, which are full Unicode characters. The lesson's words use lowercase letters a to z, 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_end and true have 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") is false. Returning true at the end of search instead of node.is_end would make it true.
    • A word is a prefix of itself. After inserting dog, starts_with("dog") is true.
    • Inserting twice. Inserting dog a second time finds every child already there and sets the flag to true again, so nothing changes.
    • A word longer than the stored one. With only dog inserted, search("dogs") and starts_with("dogs") are both false: the path stops after g.
    • Forgetting the end flag on the new word. If insert("app") is called after insert("apple") and the loop only creates missing children, search("app") still returns false unless is_end is set.
    • The empty prefix. The loop doesn't run, so starts_with returns true even for an empty trie. An empty word searched in an empty trie gives false, because the root's flag is false. The lesson's words have at least one letter, so neither case occurs.

    Testing

    • Insert apple, then search("apple"), search("app"), starts_with("app"), insert app, search("app"): true false true true.
    • Insert car and cart, then starts_with("ca"), search("ca"), starts_with("cat"), search("cart"): true false false true.
    • Insert dog twice, then search("dog"), starts_with("dog"), search("do"), starts_with("dogs"), search("dogs"): true true false false false.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free