Maintain a word collection that supports insertion and whole-word searches containing single-character wildcards.
Problem
Input. A sequence of calls to add_word(word) and search(pattern) on an initially empty WordDictionary.
Output. Insertion stores the word; each search returns whether any stored word matches the complete pattern.
Rules. A dot in a search pattern matches exactly one character, not zero or several. All other pattern characters match literally. A matching prefix alone is insufficient. Repeated insertion is idempotent. An empty pattern matches only an explicitly inserted empty word.
Example. After inserting "bat", "dad", and "mad", searching ".ad" returns True.
Searching ".a" returns False because it has length two, while all stored words have length three.
Picture
A root-to-node path spells a prefix.
State (index, node) asks whether a terminal descendant matches the remaining query suffix.
A literal follows one child; a dot tries character children, advancing the index once.
For .ad, b,a fails because the next edge is t, not d.
The d,a,d path reaches a terminal at index three.
any then skips m.
Marked alternatives are pending DFS choices, not a queue.
Problem trace
Wildcards try child alternatives; a complete match must end at a terminal node
double border complete word
- edges
- [root -> b, root -> d, root -> m, b -> ba, d -> da, m -> ma, ba -> bat, da -> dad, ma -> mad]
- words
- bat,dad,mad
- query
- .ad
double border complete wordmuted fill queued wildcard branch
- frontier
- not shown→match(1,b), match(1,d), match(1,m)
- terminal
- bat,dad,mad→not shown
double border complete wordmuted fill queued wildcard branch
- path
- not shown→root->b->ba
- next
- not shown→literal d
- frontier
- match(1,b), match(1,d), match(1,m)→not shown
double border complete wordmuted fill queued wildcard branch
- decision
- not shown→d not in {t}; false
- path
- root->b->ba→not shown
- next
- literal d→not shown
double border complete wordmuted fill queued wildcard branch
- path
- not shown→root->d->da
- decision
- d not in {t}; false→not shown
double border complete wordmuted fill queued wildcard branch
- path
- root->d->da→root->d->da->dad
double border complete word
- base case
- not shown→terminal=yes
- result
- not shown→search(".ad") = true
- path
- root->d->da->dad→not shown
- Recognize it
- A stored-prefix query contains a symbol matching any one character.
- Keep true
- match(index,node) is true exactly when a terminal descendant matches the remaining suffix.
- Reuse it
- Branch recursion only at ambiguous symbols and preserve terminal semantics at exact query length.
Reference drawing
Problem trace
Wildcards try child alternatives; a complete match must end at a terminal node
Execution trace
double border complete word
- edges
- [root -> b, root -> d, root -> m, b -> ba, d -> da, m -> ma, ba -> bat, da -> dad, ma -> mad]
- words
- bat,dad,mad
- query
- .ad
double border complete wordmuted fill queued wildcard branch
- frontier
- not shown→match(1,b), match(1,d), match(1,m)
- terminal
- bat,dad,mad→not shown
double border complete wordmuted fill queued wildcard branch
- path
- not shown→root->b->ba
- next
- not shown→literal d
- frontier
- match(1,b), match(1,d), match(1,m)→not shown
double border complete wordmuted fill queued wildcard branch
- decision
- not shown→d not in {t}; false
- path
- root->b->ba→not shown
- next
- literal d→not shown
double border complete wordmuted fill queued wildcard branch
- path
- not shown→root->d->da
- decision
- d not in {t}; false→not shown
double border complete wordmuted fill queued wildcard branch
- path
- root->d->da→root->d->da->dad
double border complete word
- base case
- not shown→terminal=yes
- result
- not shown→search(".ad") = true
- path
- root->d->da->dad→not shown
- Recognize it
- A stored-prefix query contains a symbol matching any one character.
- Keep true
- match(index,node) is true exactly when a terminal descendant matches the remaining suffix.
- Reuse it
- Branch recursion only at ambiguous symbols and preserve terminal semantics at exact query length.
Code
class WordDictionary:
def __init__(self) -> None:
self.root: dict = {}
def add_word(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault(char, {})
node[None] = True
def search(self, word: str) -> bool:
def match(index: int, node: dict) -> bool:
if index == len(word):
return None in node
if word[index] == ".":
return any(match(index + 1, child) for key, child in node.items() if key)
return word[index] in node and match(index + 1, node[word[index]])
return match(0, self.root)
The None key marks terminals, not edges.
The source’s if key excludes it because character keys are nonempty strings.
Empty queries require an inserted empty word.
Matching uses exact Python characters; query periods are wildcards, without escape syntax.
Insertion and literal lookup take expected map work for length . Wildcard work follows visited trie nodes; sufficiently branching dictionaries can require exponentially many nodes in wildcard count. Recursion uses stack space and can exceed Python’s depth limit.
Failure Check
Returning true when the query ends without checking terminal state accepts .a incorrectly.
A dot is not a regex star: it cannot consume zero or several characters.
Change to Counting Matches
New task: Count matching stored words rather than returning existence.
Picture and change: Sum all matching character branches; a terminal contributes one at exact query length.
def wildcard_count(words, pattern):
dictionary = WordDictionary()
for word in words:
dictionary.add_word(word)
def count(index, node):
if index == len(pattern):
return int(None in node)
char = pattern[index]
if char == ".":
return sum(count(index + 1, child) for key, child in node.items() if key is not None)
return count(index + 1, node[char]) if char in node else 0
return count(0, dictionary.root)
Check: Words ["bat","dad","mad","dad"] and query ".ad" return 2, not 3.
Counting cannot short-circuit after the first success.
Use when: The output needs every qualifying word’s contribution.
Change to an Iterative Frontier
New task: Avoid recursive query depth.
Picture and change: Retain all trie nodes matching the consumed prefix, then advance that frontier once per query character.
def wildcard_iterative(words, pattern):
dictionary = WordDictionary()
for word in words:
dictionary.add_word(word)
frontier = [dictionary.root]
for char in pattern:
if char == ".":
frontier = [child for node in frontier for key, child in node.items() if key is not None]
else:
frontier = [node[char] for node in frontier if char in node]
return any(None in node for node in frontier)
Check: ["bat","dad","mad"] with ".ad" returns True; ["bat"] with ".a" returns False.
Storage follows frontier width instead of recursion depth.
This version builds every level rather than taking the first depth-first success.
Both complete helpers also pay the cost of constructing their dictionaries.
Use when: Recursion safety matters more than early depth-first termination.
Transfer Check
Would memoization automatically remove the branching cost?
Answer
No. A trie has one root path per node, so these states are distinct rather than repeated equivalent subproblems.