← Whiteboard questions

Add and Search Words

Design a word list that answers searches with dot wildcards

DSA, Medium, Tries

Which structure or algorithm, and what does it cost.

Build a class WordDictionary that stores lowercase words. add_word(word) stores a word. search(pattern) returns True if some stored word matches the pattern, otherwise False. A pattern has lowercase letters and dots. A dot matches any one letter. The whole word must match, so the pattern and the word need the same length. Each example gives the calls to make, in order. Its output holds one result per call: None for add_word, True or False for search.

Examples

Input ops = [["add_word", "moon"], ["add_word", "mood"], ["search", "mood"], ["search", "mo.n"], ["search", "mo"], ["search", "moo.."]]
Output [None, None, True, True, False, False]
Why mo.n fits moon, with the dot as the second o. mo is shorter than every word. moo.. needs a five letter word.
Input ops = [["search", "."], ["add_word", "z"], ["search", "."], ["search", "z."]]
Output [False, None, True, False]
Why an empty dictionary matches nothing. One dot matches the one letter word z, but z. needs two letters.
Input ops = [["add_word", "ant"], ["add_word", "art"], ["add_word", "arc"], ["search", "a.t"], ["search", "a.c"], ["search", "ar."], ["search", "..."], ["search", "b.."], ["search", "a.e"]]
Output [None, None, None, True, True, True, True, False, False]
Why a.t fits ant and art. a.c fits arc, but only after the branch through n fails. b.. has no word starting with b. a.e fits none because no stored word ends in e.

Constraints

Your answer must contain

Target Aim for O(L) time to add a word, and a search that follows one branch per letter and tries every branch only at a dot.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A dot can stand for any letter, so a plain set lookup cannot answer a search. Think about how a search could go through the words letter by letter.

Hint 2 the approach

Store the words in a tree of letters. A normal letter in the pattern follows exactly one branch. Think about what a dot should do at that point.

Hint 3 the key step

At a dot, try every child branch and continue with the rest of the pattern. Succeed if any branch ends the pattern on a node marked as a word end.

Walkthrough

Full walkthrough brute force to best

Brute force

Keep a list of words. For a search, compare the pattern with every stored word of the same length, one letter at a time, where a dot always matches. Adding a word is O(1). A search is O(n * L) for n words of length L, and memory is O(n * L). With many words and many searches, this repeats the same letter checks again and again.

Best method

Store the words in a trie: each node maps a letter to a child and has a flag that says a word ends here. Adding walks the word and creates missing nodes, then sets the flag. To search, walk the pattern with a small recursive helper that holds the current node and the position. For a letter, follow that one child, or fail if it is missing. For a dot, try every child in turn and succeed if any of them succeeds. When the pattern is used up, the answer is the flag on the current node, which also makes sure the whole word matches and not just a start. This is correct because the walk tries every way a dot could be read, and every stored word is one path in the trie.

Hand trace

Run on example 1. Add moon and mood: they share the nodes m, o, o, then n and d are two children, both flagged. Search mood: follow m, o, o, d and d is flagged, so True. Search mo.n: follow m, o, then the dot tries the only child o, then n is a child and is flagged, so True. Search mo: follow m, o, but that node has no flag, so False. Search moo..: follow m, o, o, the first dot tries n and d, and neither has a child for the second dot, so False. The result is [None, None, True, True, False, False].

Code

class WordDictionary:
    def __init__(self):
        self.root = {}
    def add_word(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True
    def search(self, pattern):
        def go(node, i):
            if i == len(pattern):
                return "$" in node
            ch = pattern[i]
            if ch == ".":
                return any(go(child, i + 1) for key, child in node.items() if key != "$")
            return ch in node and go(node[ch], i + 1)
        return go(self.root, 0)

Time and memory

Adding is O(L). A search with no dots is O(L). Each dot can try up to 26 children, so with d dots a search is at most about 26^d * L steps, and never more than the number of nodes in the trie. With at most 3 dots this stays small. Memory is O(total letters stored).

Common mistakes

  • Treating a dot as matching zero letters or as the end of the pattern. A dot matches exactly one letter.
  • Returning True when the pattern ends on a node that is a prefix but has no end flag. With moon stored, searching mo must give False.
  • Following only the first child at a dot. If it fails, the other children must still be tried.

Related problems

More Tries problems
Add and Search Words: hints, walkthrough and Python solution