Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in Go: Trie with Dot Wildcard

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 19
    Ctrl + Enter to check

    GO · TRIES

    Design Add And Search Words Data Structure in Go, explained

    Problem overview

    The task is a WordDictionary type that stores words and finds them again, where the word you search for can contain dots. A dot matches exactly one letter. The type has three parts: Constructor returns an empty dictionary, AddWord(word string) adds a word, and Search(word string) bool says whether some added word matches. An added word matches when it has the same length and, at every position, the same letter, except that a dot in the search 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. Words added are 1 to 25 lowercase letters. A searched word has letters and at most 2 dots. There are at most 100,000 calls.

    Adding a word should take O(L) time, where L is its length. 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, with a branch at each dot

    A trie stores each word as a path of letters from a root, with a flag on the node where a word ends. Words with the same beginning share the start of their path. Adding a word walks and extends that path.

    Searching a word of plain letters is a walk down the path, and the word was added if the walk reaches a node whose end flag is set. A dot changes that, because the search can't know which child to take. It has to try all of them. That calls for recursion: a helper that answers does the rest of the word, from index i on, match a path that starts at this node? At a letter it follows the one matching child. At a dot it asks the same question of every child, and one match is enough.

    Since a dot stands for exactly one letter, the match always consumes the word position by position. A word of length 3 can only match paths of 3 letters, and a dot never matches "no letter".

    Step by step

    1. Build the node. TrieNode has children, a map[rune]*TrieNode from each next letter to its child, and isEnd, a bool that marks where an added word ends. NewTrieNode returns &TrieNode{children: make(map[rune]*TrieNode)}, because a map must be made before it can hold anything.
    2. Give the dictionary a root. WordDictionary has a field root of type *TrieNode, and Constructor creates it with NewTrieNode().
    3. Add a word. Walk from the root with a variable node. For each letter, create the child if node.children[c] is nil, then move down. After the loop, set node.isEnd = true. The flag is what makes the word count as added, and not just as the beginning of a longer word.
    4. Search through a helper. Search returns this.searchFrom(this.root, word, 0).
    5. The helper's base case. When i == len(word), every character has been matched, so the answer is node.isEnd: a word has to end exactly here.
    6. Read the current character as c := rune(word[i]). Indexing a string gives a byte, and rune(...) converts it to the type of the map's keys.
    7. At a dot, loop over every child and return true if searchFrom on that child with i + 1 returns true. If no child leads to a match, return false.
    8. At a letter, return false if node.children[c] is nil. Otherwise return the result of searchFrom on that child with i + 1. A letter has only one way to go, so there is no loop.

    The solution in Go

    type TrieNode struct {
        children map[rune]*TrieNode
        isEnd bool
    }
    
    func NewTrieNode() *TrieNode {
        return &TrieNode{children: make(map[rune]*TrieNode)}
    }
    
    type WordDictionary struct {
        root *TrieNode
    }
    
    func Constructor() WordDictionary {
        return WordDictionary{root: NewTrieNode()}
    }
    
    func (this *WordDictionary) AddWord(word string) {
        node := this.root
        for _, c := range word {
            if node.children[c] == nil {
                node.children[c] = NewTrieNode()
            }
            node = node.children[c]
        }
        node.isEnd = true
    }
    
    func (this *WordDictionary) Search(word string) bool {
        return this.searchFrom(this.root, word, 0)
    }
    
    func (this *WordDictionary) searchFrom(node *TrieNode, word string, i int) bool {
        if i == len(word) {
            return node.isEnd
        }
        c := rune(word[i])
        if c == '.' {
            for _, child := range node.children {
                if this.searchFrom(child, word, i + 1) {
                    return true
                }
            }
            return false
        }
        if node.children[c] == nil {
            return false
        }
        return this.searchFrom(node.children[c], word, i + 1)
    }
    

    With "a" and "ab" added, the searches ".", "a.", ".b" and ".." are true, and ".a" and "b" are false. For ".", the helper tries the only child of the root, a, and reaches the end of the word on a node whose flag is set, because "a" was added. For ".a", the dot goes to the child a, and that node has a child b but none named a, so the branch fails.

    Go details

    • Map iteration order is random. range node.children visits the children in a different order from run to run. That is fine here, because the helper returns true if any child matches, and the final answer doesn't depend on which one is tried first.
    • range over a map gives key and value. The loop writes _, child to ignore the letter and keep the child node.
    • Bytes versus runes. word[i] is a byte, while for _, c := range word yields runes. The map's keys are runes, so the helper converts with rune(word[i]). For lowercase letters and dots, both give the same numbers.
    • A missing key gives nil. Reading node.children[c] for a letter that isn't there returns nil and doesn't add anything, so searching never changes the dictionary.
    • A method as a helper. searchFrom starts with a lowercase letter, so it is private to the package. It is a method on *WordDictionary only so that the recursive calls read this.searchFrom; it doesn't use any field of the dictionary besides what it is given.

    Complexity

    AddWord: O(L). One step per letter, each a map lookup and possibly one node creation.

    Search: O(L) without dots. One step per letter, with a single child to follow. With dots, each dot can branch into up to 26 children, one for each lowercase letter. With at most 2 dots, the work is bounded by roughly 26 * 26 * L steps, which is still a constant factor times L. Without that limit on dots, a pattern like "......" could visit a large part of the trie.

    Space: O(N), where N is the total number of letters across the added words, at most one node per letter. The recursion adds O(L) frames.

    Edge cases and common mistakes

    • A dot never matches nothing. After adding "at", the searches "at." and "a.." are false (they need three letters), and "." is false (it needs one).
    • A prefix is not a match. "a" is the beginning of "at", but Search("a") is false. A search has to match a whole word, which is why the base case returns node.isEnd and not true.
    • A dot at the start or end. ".t" is true after adding "at".
    • An empty dictionary. Both "." and "a" give false: the root has no children, so the dot's loop finds nothing.
    • Several dots. After adding "abc", the patterns "a.c", "..c", "..." and ".b." are true, while "...." (too long) and ".bd" (wrong last letter) are false.
    • Returning after the first child at a dot. Writing return this.searchFrom(child, ...) inside the loop would try only one child. The code returns only when a branch succeeds, and moves on otherwise.
    • Returning true at the end of the loop. When no child matched, the answer is false.
    • Treating the dot like a letter. Looking up node.children['.'] would never find anything, since only letters are stored.

    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.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free