Solve LeetCode 211: Design Add and Search Words Data Structure in Python with a trie plus wildcard DFS approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Trie |
| Reusable pattern | trie plus wildcard DFS |
| Complexity | O(L) insert and O(branching^wildcards) worst-case search time |
What the problem is testing
Insert normally. During search, a dot branches to every child while a letter follows one matching edge.
Algorithm
- Insert normally. During search, a dot branches to every child while a letter follows one matching edge.
- Maintain this invariant: The DFS states represent all trie nodes consistent with the processed pattern prefix.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class WordDictionary:
def __init__(self):
self.root = {}
def addWord(self, word):
node = self.root
for char in word: node = node.setdefault(char, {})
node["$"] = True
def search(self, word):
def match(index, node):
if index == len(word): return "$" in node
char = word[index]
if char == ".":
return any(key != "$" and match(index + 1, child) for key, child in node.items())
return char in node and match(index + 1, node[char])
return match(0, self.root)Why this is correct
The proof follows the maintained state: The DFS states represent all trie nodes consistent with the processed pattern prefix. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(L) insert and O(branching^wildcards) worst-case search time. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
A wildcard matches exactly one character, and a match must end at a terminal node.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 208. Implement Trie (Prefix Tree) · Next: 212. Word Search II