Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in TypeScript: Trie with Wildcards

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

    TYPESCRIPT · TRIES

    Design Add And Search Words Data Structure in TypeScript, explained

    Problem overview

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

    • addWord(word) adds a word made of lowercase letters.
    • search(word) returns true if some added word matches word. A match has the same length and, at every position, the same letter, except that a dot in word accepts any letter.

    After adding "bad", "dad" and "mad", the search "pad" is false, "bad" is true, ".ad" is true (it matches all three words) and "b.." is true. A dot stands for exactly one letter, never for none, and a search must match a whole word: after adding "at", the search "a" is false.

    Approach

    Without dots, this is the trie of the previous kind of problem: a tree where each node is a prefix, each edge adds a letter, and a flag marks where an added word ends. Walking a word's letters from the root takes O(L) time for a word of length L.

    A dot changes the search. At a normal letter there is one way to go, but at a dot the search cannot know which child leads to a match, so it must try every child of the current node. That calls for recursion: a helper follows one path, and at a dot it calls itself once per child. If any of those calls finds a match, the answer is true. The statement limits a search to at most two dots, so the number of paths to try stays small.

    Step by step

    1. The node. TrieNode has children, of type Record<string, TrieNode> and starting as {}, which maps each next letter to its child, and isEnd, a boolean that starts as false and becomes true where an added word ends.
    2. The root. WordDictionary has a field root, a new TrieNode, the empty prefix.
    3. addWord. Start with node at the root. For each character c of the word, create the child under c if it is missing (!(c in node.children)), then move down to it. After the loop, set node.isEnd to true. Marking it is what makes the word count as added and not just as the beginning of a longer one.
    4. search. It returns what the helper answers for the root, the word and the index 0: this.searchFrom(this.root, word, 0).
    5. The helper's question. searchFrom(node, word, i) asks: does the rest of word, from index i on, match a path that starts at node?
    6. Base case. If i === word.length, every character is matched, and the answer is node.isEnd: whether an added word ends exactly here, not whether the search only passed through.
    7. The current character. c is word[i].
    8. A dot. If c === '.', any child can match. A for...in loop goes over the keys of node.children, and for each key the helper is called on node.children[key] with the next index, i + 1. If that call returns true, return true: one matching branch is enough. After the loop, return false, because no child led to a match.
    9. A letter. If c is not a key of node.children, return false. Otherwise return the helper's answer for node.children[c] and i + 1. There is only one way to go, so there is no loop: one recursive call moves one level down.

    The solution in TypeScript

    class TrieNode {
        children: Record<string, TrieNode> = {};
        isEnd: boolean = false;
    }
    class WordDictionary {
        root: TrieNode = new TrieNode();
        addWord(word: string): void {
            let node: TrieNode = 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: string): boolean {
            return this.searchFrom(this.root, word, 0);
        }
        searchFrom(node: TrieNode, word: string, i: number): boolean {
            if (i === word.length) {
                return node.isEnd;
            }
            const c: string = 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);
        }
    }
    

    Details for TypeScript:

    • for...of against for...in. for (const c of word) goes over the characters of a string, while for (const key in node.children) goes over the keys of an object. The keys here are the letters that have a child. Mixing the two up is a common slip: for...in over a string gives its indexes, and for...of over a plain object is an error.
    • word[i] reads the character at index i as a one-character string. Past the end it would be undefined, which is why the base case checks i === word.length first.
    • The type annotations are erased. Record<string, TrieNode> and const c: string exist only for the compiler; at run time children is a plain object.
    • The helper is a method. It is called as this.searchFrom(...), like any method of the class.

    Walking through an example

    Take a dictionary with "bat" and "dad", and search for ".ad". The helper is called with the part of the word already matched, then |, then the rest, and each line shows the answer. The calls finish from the deepest one upward:

    .a|d false
    .|ad false
    .ad| true
    .a|d true
    .|ad true
    |.ad true

    At the dot, the child b is tried first: "ba" exists, but "d" is not a child of it, so that branch returns false. The dot then tries d, which matches "dad" to the end, where isEnd is true. A single branch that matches is enough for the whole search to answer true.

    Complexity

    addWord: O(L) for a word of length L. search: without dots, O(L), since one path is followed. Each dot can branch into every child of its node, at most 26 of them, so with at most two dots the search tries at most 26 × 26 paths of length L, which is still O(L) when the number of dots is limited. Without that limit a search such as "......" could visit a large part of the trie. Space: O(total letters) for the nodes, plus O(L) for the call stack of a search.

    Edge cases and common mistakes

    • A dot never matches nothing. After addWord("at"), the searches "at." and "a.." are false, because they need three-letter words, and "." is false, because it needs a one-letter word.
    • A whole word, not a prefix. search("a") is false when only "at" was added. Returning true when the word runs out, instead of node.isEnd, would wrongly accept it.
    • Words of different lengths. With "a" and "ab" added, "." matches "a" and ".." matches "ab"; the dot cannot jump to a word of another length.
    • A dot in the wrong place. ".a" is false when the second letter of every added word is b, even though the dot itself has a match.
    • Returning false after the first child fails. The dot must try all children; only the loop ending without success gives false.
    • Missing the check for a letter that has no child. Reading node.children[c] for a missing key gives undefined, and the next call would fail on it.

    Testing

    Added wordsSearchesResults
    "bad", "dad", "mad""pad", "bad", ".ad", "b.."false, true, true, true
    "a", "ab"".", "a.", ".b", ".a", "..", "b"true, true, true, false, true, false
    "at""a", "at.", ".t", "a..", "."false, false, true, false, false
    "bad", "dad", "mad""...", "....", "b.d", "ba", "ban"true, false, true, false, false
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free