Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in Scala: Trie with Dot 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

    SCALA · TRIES

    Design Add And Search Words Data Structure in Scala, explained

    Problem overview

    The lesson asks for a class WordDictionary that 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 of lowercase letters and returns nothing.
    • 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", search("pad") is false, search("bad") is true, and search(".ad") and search("b..") are true. After adding "at", search("a") is false because a search must match a whole word, search(".t") is true, and search("at."), search("a..") and search(".") are false: a dot stands for exactly one letter, never for none.

    The statement gives addWord a budget of O(L), where L is the length of the word. 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. A searched word has at most two dots.

    Approach: a trie, and a search that branches at dots

    A set of words would find an exact word quickly, but a dot would force it to compare against every stored word. A trie fits better. It is a tree with one node per prefix, in which each node maps a letter to the child node for that letter, and a flag isEnd marks a node where an added word ends. Words that start the same way share their first nodes.

    Adding a word walks down from the root, creating the missing nodes along the way, and sets isEnd on the last one. This is the same as inserting into an ordinary trie, and it takes one step per letter.

    Searching with letters only is a single walk: if a letter has no child, there is no match. A dot is where the walk has to choose, because the search cannot know which child to take. So it tries every child, and one branch that matches is enough.

    This is a natural recursion. The helper searchFrom(node, word, i) answers one question: does the rest of word, from index i on, match a path that starts at node? Its cases are:

    • If i equals the length of word, every character is matched, and the answer is whether a word ends exactly at this node.
    • If the character is a dot, try searchFrom on each child with i + 1, and answer true as soon as one succeeds.
    • If the character is a letter, there is only one way to go: answer false if that child is missing, and otherwise recurse into it.

    With at most two dots, the search tries at most 26 * 26 paths in addition to the straight walk, so it stays fast.

    Step by step

    1. Write TrieNode. val children is a new empty scala.collection.mutable.Map[Char, TrieNode](), mapping each next letter to its child.
    2. Add the flag. var isEnd = false becomes true where an added word ends.
    3. Create the root in WordDictionary: val root = new TrieNode(). It stands for the empty prefix.
    4. addWord walks down. It starts with var node = root and loops over each character c of word.
    5. Create what is missing. If node.children has no key c, store new TrieNode() under it. Then node = node.children(c) moves down.
    6. Mark the end. After the loop, node.isEnd = true.
    7. search delegates. It returns searchFrom(root, word, 0), starting at the root and at index 0.
    8. The base case of searchFrom. When i == word.length, return node.isEnd: the whole word is matched, so the question is whether an added word ends here, and not whether the search merely passed through.
    9. Read the current character. val c = word(i).
    10. Handle a dot. If c == '.', loop over node.children.values, which are the child nodes. If searchFrom(child, word, i + 1) is true, return true. After the loop, return false: no child led to a match.
    11. Handle a letter. If node.children has no key c, return false. Otherwise return searchFrom(node.children(c), word, i + 1). One recursive call moves one level down, and no loop is needed.

    The solution in Scala

    class TrieNode {
        val children = scala.collection.mutable.Map[Char, TrieNode]()
        var isEnd = false
    }
    
    class WordDictionary {
        val root = new TrieNode()
    
        def addWord(word: String): Unit = {
            var node = root
            for (c <- word) {
                if (!node.children.contains(c)) {
                    node.children(c) = new TrieNode()
                }
                node = node.children(c)
            }
            node.isEnd = true
        }
    
        def search(word: String): Boolean = {
            return searchFrom(root, word, 0)
        }
    
        def searchFrom(node: TrieNode, word: String, i: Int): Boolean = {
            if (i == word.length) {
                return node.isEnd
            }
            val c = word(i)
            if (c == '.') {
                for (child <- node.children.values) {
                    if (searchFrom(child, word, i + 1)) {
                        return true
                    }
                }
                return false
            }
            if (!node.children.contains(c)) {
                return false
            }
            return searchFrom(node.children(c), word, i + 1)
        }
    }
    

    The Scala details worth a closer look:

    • Characters use single quotes. '.' is a Char, and word(i) is a Char, so c == '.' compares two characters. A string in double quotes would be a different type.
    • children.values. On a map, values gives the stored values, here the child nodes, without their letters.
    • Missing keys. node.children(c) throws a NoSuchElementException when c is not a key. The contains test comes first, so the lookup is safe.
    • return inside the for. It leaves searchFrom immediately with true. Scala 3.5 compiles this with a warning about non-local returns and runs it as expected.
    • Recursive methods need a result type. searchFrom declares : Boolean, which Scala requires because the method calls itself.

    Complexity

    Time. addWord is O(L): one map lookup and at most one node creation per letter. A search without dots is O(L). A dot branches into every child, up to 26 of them, so with at most two dots a search visits at most about 26 * 26 * L nodes, which is still O(L) for a fixed alphabet. With more dots the worst case would grow quickly, up to every node of the trie.

    Space. The trie holds at most one node per added letter, so O(T) for words with T letters in total. The recursion in search goes as deep as the searched word is long.

    Edge cases and common mistakes

    • A word that is only a prefix. After adding "at", search("a") is false. The base case returns isEnd and not true.
    • A dot at the end. After adding "cat", "car" and "cab", search("ca.") is true and search("....") is false: there are no four-letter words.
    • A dot never matches nothing. search("at.") is false after adding only "at": the dot needs a third letter, and the node for "at" has no children.
    • Only dots. search("..") matches any two-letter word. After adding "a" and "ab" it is true, because of "ab", while search(".") is true because of "a".
    • Different lengths. A word of the wrong length never matches, with or without dots, because the base case needs both the end of word and an isEnd flag at the same time.
    • Returning after the first child. At a dot, returning searchFrom's answer for the first child would miss matches under the other children. The loop returns true on a success and keeps trying on a failure.
    • An empty dictionary. search(".") returns false, because the root has no children.
    • Skipping the isEnd test. Returning true at the end of the word would make every prefix of an added word count as a word: search("ba") would be true after adding "bad".

    Testing

    • After addWord("bad"), addWord("dad") and addWord("mad"), searching "pad", "bad", ".ad" and "b.." gives false, true, true, true.
    • After addWord("a") and addWord("ab"), searching ".", "a.", ".b", ".a", ".." and "b" gives true, true, true, false, true, false.
    • After addWord("at"), searching "a", "at.", ".t", "a.." and "." gives false, false, true, false, false.
    • After adding "cat", "car" and "cab", searching "ca.", "c.t", "...", "....", ".." and "c.r" gives true, true, true, false, false, true.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free