Start learning free

LESSON 222 OF 314 · TRIES

Design Add and Search Words in Kotlin: 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

    KOTLIN · TRIES

    Design Add And Search Words Data Structure in Kotlin, explained

    Problem overview

    The class WordDictionary stores words and finds them again, where the word you search for can contain dots. A dot matches exactly one letter. It has two methods:

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

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

    The statement asks for addWord in O(L) time, where L is the length of the word. A search without dots also takes O(L). At a dot it may have to try every child of the current node. A searched word has at most 2 dots.

    Approach

    Comparing the pattern with every stored word costs time proportional to the number of words. A trie stores words letter by letter, so words with a common start share a path, and a plain letter in the pattern leads to exactly one child.

    The dot is the new part. A letter can only go one way, but a dot could be any letter, so the search has to try every child and see whether any of them leads to a match. That is a depth-first search, which a recursive helper does naturally: searchFrom(node, word, i) answers whether the part of word from index i on matches a path starting at node. With at most two dots, the branching stays small.

    Step by step

    1. Write TrieNode. It has val children, a HashMap<Char, TrieNode>() from a letter to its child node, and var isEnd, false at first. The flag becomes true on the node where an added word ends. After adding "apple", the node for "app" exists too, and only the flag says it is not a word.
    2. Give WordDictionary a root, val root = TrieNode(), the empty prefix.
    3. In addWord, walk down from the root. For each letter, if it is not in node.children, store a new TrieNode() under it. Then move into the child with node.children[c]!!. After the loop, set node.isEnd = true.
    4. Make search call the helper with the root, the word and index 0.
    5. Write the base case of searchFrom. When i == word.length, every character is matched, so return node.isEnd: the answer is whether an added word ends exactly here, not whether the search only passed through.
    6. Read the current character into val c = word[i].
    7. Handle a dot. If c == '.', loop over node.children.values, the child nodes. If searchFrom(child, word, i + 1) is true for any of them, return true: the dot can match that child's letter, and one matching branch is enough. If no child leads to a match, return false.
    8. Handle a letter. If c is not in node.children, return false. Otherwise return the result of the recursive call on node.children[c]!! with i + 1. There is no loop here, since a letter has only one way to go.

    The solution in Kotlin

    class TrieNode {
        val children = HashMap<Char, TrieNode>()
        var isEnd = false
    }
    
    class WordDictionary {
        val root = TrieNode()
    
        fun addWord(word: String) {
            var node = root
            for (c in word) {
                if (c !in node.children) {
                    node.children[c] = TrieNode()
                }
                node = node.children[c]!!
            }
            node.isEnd = true
        }
    
        fun search(word: String): Boolean {
            return searchFrom(root, word, 0)
        }
    
        fun searchFrom(node: TrieNode, word: String, i: Int): Boolean {
            if (i == word.length) {
                return node.isEnd
            }
            val c = word[i]
            if (c == '.') {
                for (child in node.children.values) {
                    if (searchFrom(child, word, i + 1)) {
                        return true
                    }
                }
                return false
            }
            if (c !in node.children) {
                return false
            }
            return searchFrom(node.children[c]!!, word, i + 1)
        }
    }
    

    Some Kotlin details in this code:

    • word[i] gives a Char, so a dot is written as the character literal '.' with single quotes, not as a string.
    • node.children.values is the collection of the map's values, here the child nodes, so for (child in node.children.values) visits every child.
    • The lookup node.children[c] has the type TrieNode?. The !! is safe because the c !in node.children check before it already returned for a missing key.
    • return false inside the dot's if comes after the loop, so it runs only when no child matched. A return false inside the loop would stop at the first child that fails.
    • The recursion goes one call deeper per letter, and the words have at most 25 letters, so the depth is small.

    Following the second example

    With "a" and "ab" added, these searches give:

    "."  -> true
    "a." -> true
    ".b" -> true
    ".a" -> false
    ".." -> true
    "b"  -> false
    

    The pattern "." tries the only child of the root, the node for a, and that node ends a word. ".a" fails because the node under a has only a b child. ".." needs a two-letter word, and "ab" is one.

    Complexity

    addWord: O(L). One map step per letter.

    search: O(L) without dots. A letter moves along a single child. A dot tries every child, and a node has at most 26 children, because the letters are lowercase. With at most 2 dots, a search visits at most about 26 × 26 × L nodes, which is still bounded by a constant times L.

    Space: O(N), with N the total number of letters in the added words. The recursion adds O(L) for the call stack.

    Edge cases and common mistakes

    • A dot never matches nothing. After adding "at", search("at.") and search("a..") are false, since they need three letters.
    • A prefix is not a match. search("a") is false after adding only "at", because the node for a doesn't end a word. That is why the base case returns node.isEnd.
    • A pattern that is too long. search("...") after adding only three-letter words works, and search("....") doesn't: the search runs out of children before it runs out of pattern.
    • Returning false too early at a dot. The result of one child must not decide the whole dot. Return true if any child matches, and false only after trying all of them.
    • Dots in addWord. Added words contain only letters. The dot is only a feature of searches.

    Testing

    addWord("bad") addWord("dad") addWord("mad")
    search("pad") search("bad") search(".ad") search("b..")  -> false true true true
    addWord("at")
    search("a") search("at.") search(".t") search("a..") search(".")  -> false false true false false
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free