SDE & MLE Prep

211. Design Add and Search Words Data Structure

Problem

Design WordDictionary with addWord(word) and search(word), where the search pattern may contain ., which matches any single letter.

Example: add "bad", "dad", "mad" → search("pad") = false, search(".ad") = true, search("b..") = true

Constraints: at most 2 dots per search; word length ≤ 25.

Trie + DFS: on ., try every child.

Complexity: add O(L); search O(26^dots · L) worst case.

class WordDictionary:
    def __init__(self):
        self.root = {}

    def addWord(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True

    def search(self, word: str) -> bool:
        def dfs(node, i):
            if i == len(word):
                return "$" in node
            ch = word[i]
            if ch == ".":
                return any(dfs(child, i + 1) for k, child in node.items() if k != "$")
            return ch in node and dfs(node[ch], i + 1)

        return dfs(self.root, 0)