Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in C++: Trie with Wildcard 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 17
    Ctrl + Enter to check

    C++ · TRIES

    Design Add And Search Words Data Structure in C++, explained

    Problem overview

    The class WordDictionary stores words and finds them again, where the word being searched for may contain dots. A dot matches exactly one letter, any letter.

    • addWord(word) adds a word made of lowercase letters (1 to 25 of them).
    • search(word) returns true if some added word matches. A match has the same length as word and the same letter at every position, except where word has a dot.

    After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true, and search("b..") is true. A search must match a whole word and a dot can't stand for nothing: after adding only "at", the searches "a", "at.", "a.." and "." are all false, while ".t" is true. A search has at most two dots, and there are at most 100,000 calls in all.

    Approach: a trie, with a branching search at dots

    Storing the words in a list and comparing against each one on every search costs time proportional to the number of words. A trie shares the letters of words that begin alike, so a search follows the letters of the query down the tree instead.

    The trie here is the one from a basic prefix-tree design: each node has a map children from a letter to the next node, and a flag isEnd that is true where an added word ends. The root stands for the empty prefix.

    With no dots, a search follows a single path, one level per letter, and takes O(L) for a word of length L. A dot is different: it can match any child, so the search doesn't know which way to go. It tries them all, and one match is enough. That makes the search recursive. A helper, searchFrom, answers one question: does the rest of the word, from index i on, match a path that starts at this node?

    • If i is the length of the word, every letter has been matched. The answer is whether a word ends exactly at this node, isEnd.
    • If the current character is a dot, try searchFrom on every child with i + 1. Return true as soon as one succeeds, and false if none does.
    • Otherwise it is a letter. If there is no child for it, return false. If there is, continue into that one child.

    Because a word has at most two dots, the search can branch at most twice, so it stays cheap: at most 26 branches at each dot.

    Step by step

    1. Define TrieNode with children, an unordered_map<char, TrieNode*>, and bool isEnd = false.
    2. Create root in the class with new TrieNode(). An empty dictionary is a root with no children.
    3. In addWord, walk down from the root with a pointer node, one letter at a time. If the current letter has no child (count(c) is 0), create one with new TrieNode(). Then move to that child.
    4. Mark the last node with isEnd = true. Without the flag, a word would be indistinguishable from the beginning of a longer one.
    5. search hands the work to the helper: searchFrom(root, word, 0), starting at the root and at index 0.
    6. Base case. When i == word.size(), return node->isEnd.
    7. Read the current character into c.
    8. Handle a dot. Loop over every entry of node->children. A range-based for with auto [letter, child] splits each entry into its key and its value. If searchFrom(child, word, i + 1) is true, return true.
    9. No child matched. After the loop, return false.
    10. Handle a letter. If node->children has no key c, return false.
    11. Otherwise recurse on node->children[c] with i + 1. A letter has only one way to go, so there is no loop.

    The solution in C++

    struct TrieNode {
        unordered_map<char, TrieNode*> children;
        bool isEnd = false;
    };
    
    class WordDictionary {
    public:
        TrieNode* root = new TrieNode();
    
        void addWord(string word) {
            TrieNode* node = root;
            for (char c : word) {
                if (!node->children.count(c)) {
                    node->children[c] = new TrieNode();
                }
                node = node->children[c];
            }
            node->isEnd = true;
        }
    
        bool search(string word) {
            return searchFrom(root, word, 0);
        }
    
        bool searchFrom(TrieNode* node, const string& word, int i) {
            if (i == word.size()) {
                return node->isEnd;
            }
            char c = word[i];
            if (c == '.') {
                for (auto [letter, child] : node->children) {
                    if (searchFrom(child, word, i + 1)) {
                        return true;
                    }
                }
                return false;
            }
            if (!node->children.count(c)) {
                return false;
            }
            return searchFrom(node->children[c], word, i + 1);
        }
    };
    

    The C++ details worth a closer look:

    • Structured bindings. auto [letter, child] unpacks each pair<const char, TrieNode*> of the map into two names. It needs C++17. The loop doesn't use letter, so some compilers warn about an unused variable; the code still works. Without structured bindings, the same loop is for (auto& entry : node->children) and entry.second.
    • const string& in the helper. The helper takes the word by reference, so the recursion doesn't copy the string at every level. const promises it won't change it. search takes its parameter by value, and then passes that copy down.
    • Signed against unsigned. i == word.size() compares an int with the unsigned size_t. Since i is never negative, the comparison is safe, though some compilers warn.
    • count before []. Reading children[c] on a missing key would insert a null entry into the map, and the next level would dereference it. The count test keeps searches from changing the map.
    • Memory. The nodes made with new are never deleted, so they live until the program ends. A long-lived program would add a destructor, or hold the children with unique_ptr.
    • Order of the map. An unordered_map visits children in no particular order, but the dot branch only asks whether any child matches, so the order doesn't change the answer.

    Complexity

    Let L be the length of the word.

    addWord: O(L). One step per letter, each an average O(1) map operation plus at most one allocation.

    search without dots: O(L). The recursion follows one path, one call per letter.

    search with dots: O(26^d * L) in the worst case, where d is the number of dots. A dot tries up to 26 children, and each branch continues for the rest of the word. With at most two dots that is at most 676 paths of up to 25 letters.

    The recursion goes as deep as the word, at most 25 levels.

    Space: O(total letters added). Each word adds at most one node per letter, and words with a common beginning share their nodes. The recursion's extra space is O(L).

    Edge cases and common mistakes

    • A word that is only a beginning. After adding "at", search("a") is false, because the node for a has no isEnd. The base case returns the flag, not true.
    • A dot stands for exactly one letter. search("at.") and search("a..") are false after adding "at", because the search runs out of children before the word runs out of characters. search(".") is false too, because "at" has two letters.
    • Dot at the end or the start. search(".t") is true after adding "at", and search("..") is true after adding "ab".
    • Several words of different lengths. After adding "a" and "ab", search(".") matches the first and search("..") the second. A dot never matches a longer word, since the flag is checked only when the query ends.
    • A dot where no child leads to a match. After adding "a" and "ab", search(".a") is false: the dot tries the node for a, which has a child b but not a.
    • Returning true from the first child of a dot. A dot has to try every child until one succeeds. Returning the first child's answer would miss matches that sit under another child.
    • Returning from the loop too early with false. The return false belongs after the loop, not inside it.
    • Treating the base case as success. When the query is used up, the node must also be marked as the end of an added word.

    Testing

    • Add "bad", "dad", "mad", then search "pad", "bad", ".ad", "b..": false, true, true, true.
    • Add "a", "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 "bad", "bat", "cat", then search "ba.", "..t", "...", ".a.", "b.d", "c..": all true.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free