Start learning free

LESSON 503 OF 671 · TRIES

Design Add and Search Words in JavaScript: Trie with Wildcard Dots

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

    JAVASCRIPT · TRIES

    Design Add And Search Words Data Structure in JavaScript, explained

    Problem overview

    The task is to implement a class WordDictionary with two methods:

    • addWord(word) stores a word made of lowercase letters.
    • search(word) returns true if some stored word matches. The searched word may contain dots, and a dot matches exactly one letter. A match must have the same length as the searched word and the same letter at every position that isn't a dot.

    After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true because the dot matches the b, d or m, and search("b..") is true. A dot never matches zero letters: after adding only "at", search("at.") is false, and search("a") is false because a search matches a whole word, not the beginning of one.

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

    Approach: a trie, and a recursive search at dots

    The words are stored in a trie, a tree with one node per prefix, where each node maps a letter to its child and has an isEnd flag that marks the end of a stored word. Adding a word walks down from the root, creating the missing nodes, and flags the last one.

    Searching a word without dots follows one path: each letter has at most one child to go to. A dot breaks that, because the search can't know which child to take. It has to try every child, and one matching branch is enough. So the search becomes a recursion that remembers how far into the word it is:

    • If every character has been matched, the answer is whether a stored word ends at the current node.
    • If the current character is a letter, take that child if it exists, and continue from there.
    • If it is a dot, try every child, and return true as soon as one of them leads to a match.

    The statement allows at most two dots in a search, which keeps the branching small. Every added word is made of lowercase letters, so a node has at most 26 children.

    Here is how many calls the helper makes on a dictionary holding "bad", "dad" and "mad":

    searchresultcalls of searchFrom
    "pad"false1
    "bad"true4
    ".ad"true4
    "b.."true4

    "pad" stops at once because the root has no child p. For ".ad", the dot tries the child b first, the rest "ad" matches below it, and the search returns true without looking at d or m.

    Step by step

    1. Give TrieNode an empty object for children. It maps each next letter to its child node.
    2. Set isEnd to false. It becomes true on the node where an added word ends. After adding "apple", the nodes for "app" and "apple" both exist, and only this flag tells them apart.
    3. Create the root in the constructor. It stands for the empty prefix.
    4. In addWord, start node at the root.
    5. Loop over the letters of word with for...of.
    6. Create a missing child: if c is not a key of node.children, store a new TrieNode under it.
    7. Move down to node.children[c].
    8. Mark the end with node.isEnd = true after the loop.
    9. Make search a one-liner. It returns this.searchFrom(this.root, word, 0): start at the root, at index 0.
    10. Write the base case of searchFrom. When i equals word.length, every character is matched, so return node.isEnd. Passing through a node isn't enough: a word must end exactly here.
    11. Read the current character into a const named c.
    12. Check for a dot. A dot can match any child.
    13. Loop over the keys of node.children with for...in. The child for a key is node.children[key].
    14. Recurse into each child with the next index, i + 1, and return true as soon as one call does.
    15. After the loop, return false. No child led to a match.
    16. Handle a letter that has no child. If c is not a key of node.children, return false.
    17. Otherwise follow the letter: return the result of searchFrom on node.children[c] with i + 1. A letter has only one way to go, so there is no loop.

    The solution in JavaScript

    class TrieNode {
        constructor() {
            this.children = {};
            this.isEnd = false;
        }
    }
    
    class WordDictionary {
        constructor() {
            this.root = new TrieNode();
        }
    
        addWord(word) {
            let node = this.root;
            for (const c of word) {
                if (!(c in node.children)) {
                    node.children[c] = new TrieNode();
                }
                node = node.children[c];
            }
            node.isEnd = true;
        }
    
        search(word) {
            return this.searchFrom(this.root, word, 0);
        }
    
        searchFrom(node, word, i) {
            if (i === word.length) {
                return node.isEnd;
            }
            const c = word[i];
            if (c === '.') {
                for (const key in node.children) {
                    if (this.searchFrom(node.children[key], word, i + 1)) {
                        return true;
                    }
                }
                return false;
            }
            if (!(c in node.children)) {
                return false;
            }
            return this.searchFrom(node.children[c], word, i + 1);
        }
    }
    

    The JavaScript details worth a closer look:

    • for...of against for...in. for (const c of word) goes over the characters of a string. for (const key in node.children) goes over the keys of an object, and each key is a string. Mixing them up is a common slip: for...in over a string gives its indexes, not its letters.
    • word[i] reads one character of a string as a one-character string, so it can be compared with '.' using ===.
    • in tests for a key. !(c in node.children) is true when no child exists for c. The parentheses matter, because !c in node.children would negate c first.
    • this.searchFrom. The recursive calls need the this. prefix, because searchFrom is a method of the class.
    • The return value is a boolean. node.isEnd is true or false, and the other returns are literals, so search always returns a boolean.
    • Early return from a loop. The return true inside the loop leaves the whole function, so the remaining children are not tried.

    Complexity

    addWord: O(L) time. One step per letter, with at most one node created per step.

    search without dots: O(L) time. One recursive call per letter, and one more at the end.

    search with dots: each dot can multiply the work by the number of children of the nodes it reaches, at most 26. With at most two dots the worst case is about 26 * 26 * L steps, which is still O(L) for a fixed alphabet and at most two dots. Without the limit on dots, the cost could grow much faster, as a trie with many words and many dots has many paths to try.

    Space: O(N) for the trie, where N is the total number of letters in the added words, less where prefixes are shared. The search uses O(L) stack space for its recursion.

    Edge cases and common mistakes

    • A dot matches exactly one letter. After adding "at", search("at.") and search("a..") are false, since they need three-letter words, and search(".") is false, since it needs a one-letter word.
    • A prefix is not a match. After adding "at", search("a") is false. The base case returns node.isEnd, not true.
    • Words of different lengths. After adding "a" and "ab": search(".") is true, search("..") is true, and search(".a") is false, because no added word has a as its second letter.
    • An empty dictionary. search(".") returns false: the root has no children, so the dot has nothing to try.
    • Forgetting to return false after the dot loop. The function would carry on and treat '.' as a letter, which isn't a key of any node.
    • Ignoring the result of the recursive call at a dot. Each call has to be tested with if. Returning the first child's answer directly would give up on the other children.
    • Checking isEnd too early. The check belongs to the base case, after every character has been matched.
    • Adding a word with a dot. Only searches contain dots. A dot added to the trie would become a child like any other letter.

    Testing

    Results of the search calls, in order:

    • 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.
    • Search "." and "a" in an empty dictionary: false false.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free