Start learning free

LESSON 505 OF 673 · TRIES

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

    PYTHON · TRIES

    Design Add And Search Words Data Structure in Python, explained

    Problem overview

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

    • addWord(word) adds a word of lowercase letters.
    • search(word) returns True if some added word matches. A match has the same length as the search word and the same letter at every position, 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 never stands for zero letters. After adding only "at", search("a") is False, because a search has to match a whole word, and search("at.") is False because it needs three letters. Search words contain at most two dots.

    Approach: a trie, and a branch at every dot

    A trie stores words letter by letter: each node has a children dictionary from a letter to the next node, and an isEnd flag that marks where an added word finishes. Words with the same beginning share nodes. Adding a word walks down from the root, creating missing nodes, and marks the last one with isEnd = True. That takes O(L) for a word of length L.

    Searching a word with only letters is the same walk: follow each letter, give up if a child is missing, and at the end return isEnd, since the match must end exactly where an added word ends.

    A dot is the new part. The search can't know which letter it stands for, so it tries every child of the current node. If any one of them leads to a match for the rest of the word, the search succeeds. That calls for a recursive helper, searchFrom(node, word, i), which answers one question: does word, from index i on, match a path that starts at node?

    • If i equals len(word), every character is matched, and the answer is node.isEnd.
    • If word[i] is a letter, there is only one way to go: down that child if it exists, otherwise False.
    • If word[i] is a dot, try each child with index i + 1 and return True as soon as one succeeds.

    The cost grows with dots. A word without dots takes O(L). Each dot can multiply the work by at most the number of children of a node, 26 here, and a search has at most two dots, so the worst case is bounded by a constant times L.

    Step by step

    1. Give TrieNode a children dict that will map each next letter to its child node.
    2. Add isEnd, starting as False. It becomes True where an added word ends.
    3. Create the root in WordDictionary.__init__: self.root = TrieNode().
    4. In addWord, start node at self.root.
    5. Loop over each character c of word, going one level down per letter.
    6. Create a missing child when c is not in node.children.
    7. Move down to node.children[c].
    8. Mark the end with node.isEnd = True after the loop.
    9. Let search delegate. It returns self.searchFrom(self.root, word, 0): start at the root, at index 0.
    10. Write the base case of searchFrom. When i == len(word), return node.isEnd. Passing through a word's node isn't enough, because the match must end where an added word ends.
    11. Read the current character c = word[i].
    12. Branch on a dot. If c == '.', any child can match.
    13. Loop over the child nodes with node.children.values().
    14. Recurse on each child with i + 1, and return True as soon as one call does. One matching branch is enough.
    15. Return False after the loop. No child led to a match.
    16. Handle a letter. If c is not in node.children, return False.
    17. Otherwise recurse into node.children[c] with i + 1 and return its answer. There is no loop, since a letter has one way to go.

    The solution in Python

    class TrieNode:
        def __init__(self):
            self.children = {}
            self.isEnd = False
    
    
    class WordDictionary:
        def __init__(self):
            self.root = TrieNode()
    
        def addWord(self, word: str) -> None:
            node = self.root
            for c in word:
                if c not in node.children:
                    node.children[c] = TrieNode()
                node = node.children[c]
            node.isEnd = True
    
        def search(self, word: str) -> bool:
            return self.searchFrom(self.root, word, 0)
    
        def searchFrom(self, node: TrieNode, word: str, i: int) -> bool:
            if i == len(word):
                return node.isEnd
            c = word[i]
            if c == '.':
                for child in node.children.values():
                    if self.searchFrom(child, word, i + 1):
                        return True
                return False
            if c not in node.children:
                return False
            return self.searchFrom(node.children[c], word, i + 1)
    

    Python details worth a closer look:

    • dict.values(). It gives the dictionary's values, which here are the child nodes, so the loop never needs the letters themselves. The dictionary isn't changed during the loop, so iterating it is safe.
    • Early return from inside a loop. The return True in the loop ends searchFrom at once and passes True up through every caller. The return False comes after the loop, so it only runs when no child matched.
    • Calling the helper. The recursion goes through self, as in self.searchFrom(...). A bare searchFrom(...) would raise NameError.
    • A fresh dict per node. self.children = {} is set in __init__, so every node has its own. A dict defined in the class body would be shared by all nodes.
    • Indexing and the base case. word[i] would raise IndexError at i == len(word). The base case comes first for that reason.

    Complexity

    Time. addWord is O(L). A search without dots is O(L): one dictionary lookup per letter. At a dot, the search tries every child of the node, up to 26. With at most two dots, the number of paths the search follows is at most 26 × 26, and each path is at most L steps long. So a search is bounded by a constant times L, and the dots are the part that makes it slower than a plain trie lookup.

    Space. The trie takes space for each distinct prefix of the added words, at most the total number of letters added. The recursion depth is at most L, at most 25 here.

    Edge cases and common mistakes

    • A dot needs exactly one letter. After adding "at", search("at.") is False and search(".") is False, while search(".t") is True. The dot has to consume a letter, so word length must agree.
    • A prefix isn't a match. search("a") is False after adding "at", because the node for "a" has no isEnd. That is why the base case returns node.isEnd and not True.
    • Words of different lengths. After adding "a" and "ab", search(".") is True through "a", search("..") is True through "ab", and search(".a") is False, since no added word has a second.
    • Every dot, not only the first. A dot in the middle, as in "b.d", works the same way: the recursion carries on from the child it chose.
    • Dots only. search("...") with "bad", "dad" and "mad" added is True.
    • Searching an empty dictionary. search(".") returns False: the root has no children to try.
    • Returning inside the loop too early. Writing return self.searchFrom(...) directly in the loop would return the first child's answer and never try the others. The code returns only when a child matches.
    • Treating a dot as a key. addWord only receives letters, so '.' is never a key in children. A dot in a search is handled by trying all children.

    Testing

    • Add "bad", "dad", "mad"; then search("pad"), search("bad"), search(".ad"), search("b.."): False, True, True, True.
    • Add "a", "ab"; then search("."), search("a."), search(".b"), search(".a"), search(".."), search("b"): True, True, True, False, True, False.
    • Add "at"; then search("a"), search("at."), search(".t"), search("a.."), search("."): False, False, True, False, False.
    • With nothing added, search("a") and search("."): False, False.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free