Start learning free

LESSON 222 OF 314 · TRIES

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

    SWIFT · TRIES

    Design Add And Search Words Data Structure in Swift, explained

    Problem overview

    The class WordDictionary stores words and finds them again, where the word being searched may contain dots. A dot matches any one letter. It has two methods:

    • addWord(_ word: String) adds a word made of lowercase letters.
    • search(_ word: String) -> Bool returns true if some added word matches. An added word matches when it has the same length and, at every position, the same letter; where the search word has a dot, any letter matches.

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

    The statement asks for addWord in O(L) time, where L is the length of the word. A search without dots takes O(L) too; at a dot it may have to try every child of the node it has reached. Search words have at most two dots.

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

    A trie stores words letter by letter: each node stands for a prefix, a map takes the next letter to the child node, and a flag marks the nodes where an added word ends. Words that start the same way share nodes.

    Without dots, a search follows one child per letter and finishes by checking the flag, so it costs O(L). With a dot, the search can't know which child to follow, so it tries all of them and succeeds if any one leads to a match. That is a natural recursion: a helper searchFrom(node, word, i) answers whether the rest of word, from index i on, matches a path that starts at node.

    • When i equals the length of the word, every character is matched, and the answer is whether a word ends at this node.
    • When the character is a dot, try searchFrom on every child with i + 1, and answer true as soon as one succeeds.
    • When it is a letter, follow the one child for that letter if it exists, and answer false if it doesn't.

    The cost of a dot is bounded by the alphabet: a node has at most 26 children, and a search word has at most two dots, so a search tries at most about 26 × 26 branches beyond the plain path. That keeps each search fast.

    Take the search ".ad" in a dictionary holding "bad", "dad" and "mad". The root has the children b, d and m. The dot tries the children until one works. From b, the letters a and d follow the path of "bad", and the flag is set there, so that branch answers true. The branches through d and m would answer true as well.

    Step by step

    1. Give TrieNode its children: var children: [Character: TrieNode] = [:], a dictionary from each next letter to the child node.
    2. Add the word-end flag: var isEnd = false, which becomes true on the node where an added word ends.
    3. Give WordDictionary a root: let root = TrieNode(), standing for the empty prefix.
    4. In addWord, start at the root with var node = root, and loop over the characters of word.
    5. Create a missing child. If node.children[c] is nil, store a new TrieNode() there.
    6. Move down with node = node.children[c]!. The ! is safe because the child exists by now.
    7. Mark the end. After the loop, set node.isEnd = true.
    8. Write search as one line. It returns what searchFrom answers for root, Array(word) and index 0. A Swift String can't be indexed with an integer, and an array of Character values can.
    9. Start searchFrom with the base case. If i == word.count, return node.isEnd: the whole word is matched, and what counts is whether an added word ends exactly here.
    10. Read the current character into let c = word[i].
    11. Branch on a dot. If c == ".", any child can match, so the code tries them all.
    12. Loop over node.children.values, the child nodes.
    13. Recurse into each child with i + 1, and return true if the recursive call returns true. One matching branch is enough.
    14. Return false after the loop. No child led to a match.
    15. Handle a letter. After the dot's if, c is a letter, so if node.children[c] is nil, return false.
    16. Follow the single path. Otherwise return searchFrom(node.children[c]!, word, i + 1). A letter has only one way to go, so there is no loop.

    The solution in Swift

    class TrieNode {
        var children: [Character: TrieNode] = [:]
        var isEnd = false
    }
    
    class WordDictionary {
        let root = TrieNode()
    
        func addWord(_ word: String) {
            var node = root
            for c in word {
                if node.children[c] == nil {
                    node.children[c] = TrieNode()
                }
                node = node.children[c]!
            }
            node.isEnd = true
        }
    
        func search(_ word: String) -> Bool {
            return searchFrom(root, Array(word), 0)
        }
    
        func searchFrom(_ node: TrieNode, _ word: [Character], _ i: Int) -> Bool {
            if i == word.count {
                return node.isEnd
            }
            let c = word[i]
            if c == "." {
                for child in node.children.values {
                    if searchFrom(child, word, i + 1) {
                        return true
                    }
                }
                return false
            }
            if node.children[c] == nil {
                return false
            }
            return searchFrom(node.children[c]!, word, i + 1)
        }
    }
    

    The Swift details worth a closer look:

    • Strings and arrays. Array(word) turns a String into a [Character], so word[i] works. It is done once in search, and the array is passed down the recursion, so the conversion isn't repeated at each level.
    • Comparing a Character with ".". In c == ".", Swift reads the literal as a Character because c is one, so the comparison compiles without conversion.
    • Dictionary lookups are optionals. node.children[c] has the type TrieNode?. The code checks for nil before it applies !, because forcing a nil crashes the program.
    • children.values. It is a collection of the dictionary's values, the child nodes, without their letters. A dictionary has no defined order, so the children may be tried in any order. That doesn't change the answer, because the result is true if any branch matches.
    • Classes are reference types. Passing a TrieNode to searchFrom passes a reference to the same node, not a copy, so the search is cheap, and root as a let still lets its contents change.
    • Calling a method from another method. search calls searchFrom without self., which Swift allows inside a class's methods.

    Complexity

    addWord: O(L). One dictionary lookup, and possibly one node creation, per letter.

    search without dots: O(L). One child is followed per letter. Converting the word to an array is also O(L).

    search with dots: each dot multiplies the work by at most the number of children, which is at most 26. With at most two dots, a search visits at most about 26 × 26 × L nodes. The depth of the recursion is at most L.

    Space: O(N) for the trie, in the total number of letters over all added words, in the worst case. A search needs O(L) extra space for the array of characters and the recursion.

    Edge cases and common mistakes

    • A prefix is not a match. After adding "at", search("a") is false: the path exists, but no word ends there. That is the job of the isEnd check in the base case.
    • A dot never matches nothing. search("at.") needs a three-letter word, so it is false when only "at" was added. search(".") is false there as well, since "at" has two letters. The recursion only moves to a child when it matches one character, so lengths must agree.
    • A dot at the end of a longer search. With "a" and "ab" added, search(".") is true because "a" ends at the first level, search("..") is true because of "ab", and search(".a") is false because no word has a second letter "a".
    • All dots. After adding "bad", "dad" and "mad", search("...") is true and search("....") is false.
    • Returning true as soon as the letters run out. That would make every prefix a match. The base case returns node.isEnd.
    • Returning the result of the first child only. In the dot branch, the code must return true only when a child succeeds, and keep trying the others when one fails. The return false comes after the loop.
    • Forgetting to advance i. Calling searchFrom(child, word, i) would match the same dot again and recurse without end.

    Testing

    • Added "bad", "dad", "mad": search("pad"), search("bad"), search(".ad"), search("b..") give false, true, true, true.
    • Added "a", "ab": search("."), search("a."), search(".b"), search(".a"), search(".."), search("b") give true, true, true, false, true, false.
    • Added "at": search("a"), search("at."), search(".t"), search("a.."), search(".") give false, false, true, false, false.
    • Added "bad", "dad", "mad": search("...") gives true and search("....") gives false.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free