Start learning free

LESSON 222 OF 314 · TRIES

Add and Search Words in Rust: Trie with Wildcard Dots, DFS

Practice O(L) Read the full explanation

Design a data structure that stores words and finds them again, where the word you search for may contain dots: a dot '.' matches any one letter.

Implement the class WordDictionary:

  • WordDictionary() creates an empty dictionary of words.
  • addWord(word) adds word to it.
  • search(word) returns true if some added word matches word, and false otherwise. An added word matches when it has the same length and, at every position, the same letter as word; where word has a dot, any letter matches.

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

 

Example 1:

Input:
    addWord("bad")
    addWord("dad")
    addWord("mad")
    search("pad")
    search("bad")
    search(".ad")
    search("b..")
Output: false true true true
Explanation: "pad" was never added. ".ad" matches "bad", "dad" and "mad", and "b.." matches "bad".

Example 2:

Input:
    addWord("a")
    addWord("ab")
    search(".")
    search("a.")
    search(".b")
    search(".a")
    search("..")
    search("b")
Output: true true true false true false
Explanation: "." matches the one-letter word "a", and "a.", ".b" and ".." all match "ab". No added word has "a" as its second letter, and "b" was never added.

Example 3:

Input:
    addWord("at")
    search("a")
    search("at.")
    search(".t")
    search("a..")
    search(".")
Output: false false true false false
Explanation: A dot stands for exactly one letter, never for none, so "at." and "a.." need a three-letter word and "." a one-letter word. "a" is the beginning of "at", but a search must match a whole word.

 

Constraints:

  • 1 <= word.length <= 25
  • A word passed to addWord consists of lowercase English letters, a to z.
  • A word passed to search consists of lowercase English letters and dots, with at most 2 dots.
  • At most 105 calls in total are made to addWord and search.

Note:

addWord should run in O(L) time, where L is the length of the word. A search without dots takes O(L) time too; at a dot it may have to try every child of the node it has reached.

STEP 1 OF 20
    Ctrl + Enter to check

    RUST · TRIES

    Design Add And Search Words Data Structure in Rust, explained

    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 answer true as soon as one returns true.
    • A letter: if the node has no such child, answer false. Otherwise recurse into that one child with i + 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

    1. Declare TrieNode. Its fields are children: HashMap<char, TrieNode> and is_end: bool. A struct can hold a map of its own type because the HashMap keeps its values on the heap.
    2. Write TrieNode::new with an empty map and is_end set to false.
    3. Declare WordDictionary. It has one field, root: TrieNode, the node of the empty prefix. WordDictionary::new returns one with TrieNode::new() as the root.
    4. add_word starts with let mut node = &mut self.root; and loops over word.chars(). For each letter it inserts a new TrieNode if the key is missing (contains_key(&c) takes a reference), and moves down with get_mut(&c).unwrap(). After the loop it sets node.is_end = true.
    5. Collect the characters in search. let chars: Vec<char> = word.chars().collect();, because a String can't be indexed by position, and the helper reads word[i].
    6. Delegate to the helper. search returns Self::search_from(&self.root, &chars, 0). The helper has no self, so it is called through Self::, and &chars lends the vector as the slice &[char] that the helper expects.
    7. The base case. In search_from, if i == word.len(), return node.is_end.
    8. Read the current character: let c = word[i];.
    9. Handle a dot. If c == '.', loop over node.children.values(), the child nodes. If Self::search_from(child, word, i + 1) is true, return true at once. If the loop ends, no child led to a match, so return false.
    10. Handle a letter. If node.children has no key c, return false.
    11. 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] and Vec<char>. A slice borrows a run of elements without owning them. Passing &chars, a reference to a Vec<char>, works where &[char] is expected, because Rust converts the reference automatically. The recursion passes the same slice down and changes only the index i, so no copy is made at any level.
    • Why not index the string? A String is UTF-8 bytes, so word[i] doesn't compile on it. Turning it into a vector of char gives constant-time indexing by character.
    • values() iterates over a map's values, here shared references to the child nodes, which is what search_from takes. The order is unspecified for a HashMap, which doesn't matter: the search wants any one match.
    • Early return inside a loop. return true leaves the whole function, not only the loop, so the first matching child ends the search. return false after the loop runs only if no child matched.
    • Shared references in the search. search takes &self and 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_word treats every character as a letter. The lesson guarantees added words have only lowercase letters.
    • Last expression. The final call in search_from has 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 at added, search("at.") is false, because after t there is no child to match the dot. search(".") is false too, because a one-letter word was never added.
    • A prefix isn't a match. search("a") with only at added is false. The base case checks is_end, not just that the path exists.
    • Different lengths. With a and ab added, search("..") is true and search(".a") is false. Length is decided by the end flag at the end of the search word.
    • A dot at the start, middle or end. search(".ad") and search("b..") both match bad. The code treats a dot the same way at every position.
    • Returning false too 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, returns false.
    • Returning true for an empty dictionary. Without words, every search fails: the root has no children, so any letter or dot reaches false.
    • 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 search pad, bad, .ad, b..: false true true true.
    • Add a and ab, then search ., a., .b, .a, .., b: true true true false true false.
    • Add at, then search a, at., .t, a.., .: false false true false false.
    • Add cat, car, cab, then search ca., c.t, ..., .., ....: true true true false false.
    • Search a and . in an empty dictionary: 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