Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in C#: Trie with Wildcard Dot Search

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

    You implement a class WordDictionary that stores words and finds them again, where the searched word may contain dots. A dot matches exactly one letter, any letter. AddWord(string word) stores a word. Search(string word) returns true if some stored word matches: it must have the same length, the same letter at every position where word has a letter, and any letter where word has a dot.

    After adding "bad", "dad" and "mad", Search("pad") is false, Search("bad") is true, Search(".ad") is true because it matches all three words, and Search("b..") is true. A dot never stands for "no letter": with only "at" stored, Search("at.") and Search(".") are false. A search must match a whole word, so Search("a") is false, even though "a" begins "at".

    Added words have 1 to 25 lowercase letters, and searched words have at most 2 dots. AddWord should run in O(L) time, and a search without dots in O(L) too.

    Approach: a trie, and a recursive walk that branches at dots

    A trie suits this problem. It stores words letter by letter in a tree, with one node per prefix. Each TrieNode has a dictionary children that maps a letter to the next node, and a flag isEnd that marks where an added word ends. The flag is needed because the node for "app" exists after adding "apple", but only a word that was added as a whole should be found by a search.

    Adding a word walks down from the root, creating any missing child, and sets isEnd on the last node.

    Searching without dots is the same walk: follow the letters, and if a letter has no child, the answer is false. With dots, the walk can't know which child to take. A dot has to be tried against every child. That calls for recursion: a helper SearchFrom(node, word, i) answers the question "does the rest of word, from index i on, match some path that starts at node?"

    • If i equals word.Length, every character is matched. The answer is whether a word ends exactly here: node.isEnd.
    • If the current character is a letter, there is one way to go: the child under that letter, or false if there is none.
    • If it is a dot, try every child. One branch that matches is enough, so return true at the first success. If no child works, return false.

    Without dots, each step is a single dictionary lookup, so a search costs O(L). A dot multiplies the work by at most the number of children, at most 26 for lowercase letters. With at most two dots in a search, that stays small.

    Some searches on a dictionary holding only "hello" give these results: "hello" true, "hell" false, "h.llo" true, "h.l.." true, "....." true, and "...." false, since the pattern is one letter too short.

    Step by step

    1. Declare children in TrieNode as a public Dictionary<char, TrieNode> set to a new empty dictionary.
    2. Declare isEnd as a public bool set to false.
    3. Declare root in WordDictionary as a new TrieNode. It stands for the empty prefix.
    4. In AddWord, start node at root and loop over the letters. If node.children lacks the letter (ContainsKey), store a new TrieNode under it. Then move down to that child.
    5. After the loop, set node.isEnd = true.
    6. Write Search as one line: return what SearchFrom says for root, word and index 0.
    7. In SearchFrom, write the base case. When i == word.Length, return node.isEnd.
    8. Read the current character with char c = word[i].
    9. Handle a dot. If c == '.', loop over node.children.Values. If SearchFrom(child, word, i + 1) is true, return true. After the loop, return false: no child led to a match.
    10. Handle a letter. If node.children has no key c, return false. Otherwise return the result of SearchFrom on node.children[c] with i + 1. There is no loop, because a letter has only one way to go.

    The solution in C#

    class TrieNode {
        public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
        public bool isEnd = false;
    }
    class WordDictionary {
        TrieNode root = new TrieNode();
        public void AddWord(string word) {
            TrieNode node = root;
            foreach (char c in word) {
                if (!node.children.ContainsKey(c)) {
                    node.children[c] = new TrieNode();
                }
                node = node.children[c];
            }
            node.isEnd = true;
        }
        public bool Search(string word) {
            return SearchFrom(root, word, 0);
        }
        bool SearchFrom(TrieNode node, string word, int i) {
            if (i == word.Length) {
                return node.isEnd;
            }
            char c = word[i];
            if (c == '.') {
                foreach (TrieNode child in node.children.Values) {
                    if (SearchFrom(child, word, i + 1)) {
                        return true;
                    }
                }
                return false;
            }
            if (!node.children.ContainsKey(c)) {
                return false;
            }
            return SearchFrom(node.children[c], word, i + 1);
        }
    }
    

    The C# details worth knowing:

    • Characters and strings use different quotes. '.' is a char, and c == '.' compares two chars. Writing c == "." would not compile, because a char can't be compared with a string.
    • A missing key throws. node.children[c] throws KeyNotFoundException if c is absent, so the code checks ContainsKey first. Assigning node.children[c] = ... adds the key without any check.
    • Dictionary.Values is a collection of the stored nodes, which a foreach can walk. The dictionary must not be changed during that loop. Search only reads it.
    • The helper is private. SearchFrom has no access modifier, so it is private to the class, which is what you want for a helper. AddWord and Search are public and PascalCase. Code ported from Java or Python often has addWord, which doesn't match these names.
    • The recursion is as deep as the word. At most 25 levels, so there is no risk to the call stack.
    • Printing a bool shows True or False in C#, with capital letters.

    Complexity

    Time. AddWord is O(L), one dictionary operation per letter. A Search without dots is O(L) too. Each dot can branch into as many calls as the node has children, up to 26, so a search with d dots takes about O(26^d * L) in the worst case. The lesson limits searches to two dots, so this is bounded by a constant times L.

    Space: O(N) for the trie, where N is the number of nodes created, at most the total length of all added words. The recursion adds at most L frames while a search runs.

    Edge cases and common mistakes

    • Empty dictionary. Search("a") and Search(".") are both false: the root has no children.
    • A dot needs a letter. With "at" stored, "." is false because "at" has two letters, and "at." is false because it needs three.
    • Prefix only. Search("a") is false when only "at" is stored. The base case returns node.isEnd, not true.
    • All dots. ".." matches any stored two-letter word. With "a" and "ab" stored it is true because of "ab", and "." is true because of "a".
    • Dots in different places. With "a" and "ab" stored, "a." and ".b" are true, while ".a" is false because no stored word has "a" as its second letter.
    • Returning the result of the first child only. At a dot, the loop must continue to the next child when one branch fails. Returning that branch's result straight away would miss matches in later children.
    • Treating '.' as a stored letter. Words are added with letters only. A dot is only meaningful in a search.

    Testing

    • Add "bad", "dad", "mad", then search "pad", "bad", ".ad", "b.." to get false, true, true, true.
    • Add "a" and "ab", then search ".", "a.", ".b", ".a", "..", "b" to get true, true, true, false, true, false.
    • Add "at", then search "a", "at.", ".t", "a..", "." to get false, false, true, false, false.
    • On an empty dictionary, search "a" and "." to get false and false.
    • Add "hello", then search "hello", "hell", "h.llo", "h.l..", ".....", "...." to get true, false, true, true, true, false.
    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