Skip to content
mlmentorship

Branch at wildcards and require an exact terminal match

Follow trie edges for literals, explore character alternatives at each dot, then change existence into counting or iterative matching.

Published · 17 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Branch at wildcards and require an exact terminal match

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

A literal follows one child; a dot recursively tries each child until one full-length terminal path succeeds.

Problem trace

Wildcards try child alternatives; a complete match must end at a terminal node

Wildcards try child alternatives; a complete match must end at a terminal nodeLiterals follow matching trie edges. A dot tries each child for one character. Here a cannot satisfy the final d; e reaches bed. A full pattern matches only at a stored word's terminal node. Prefix ba exists but is not a word.Try child alternatives, then requirea terminal matchStored words: bake and bedb.dTry bothchildrenNeed d; onlyk existsbaekdeTerminal bed:trueba reaches a, but a has no word flag:false.The dot uses one character. Thesuffix still must match.
A dot tries child alternatives before the remaining suffixThe same bake/bed fixture as the screen lesson. The a branch lacks d; the e branch reaches terminal bed.Pattern b.d: try each child for thedotb.dStored words: bake and bedbaekdetry bothneed d; onlykbed: trueDouble ring: a stored word ends here.
A complete pattern succeeds only at a stored word terminalThe existing ba prefix is not a word. The complete b.d pattern matches bed; each dot consumes one character.The complete query must end at a wordflagQuery babaano wordflagExisting prefix; falseQuery b.db.ddbedComplete stored word; trueThe dot consumes exactly onecharacter.
Read it this way: Literals follow matching trie edges. A dot tries each child for one character. Here a cannot satisfy the final d; e reaches bed. A full pattern matches only at a stored word's terminal node. Prefix ba exists but is not a word. Why is the existing ba path insufficient while b.d reaches a stored word?
Full interview answer 17 min read

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

Input and goalStore words and support `.` as a wildcard that matches any one character.
Store three terminal pathsbat, dad, and mad share root but have separate first-letter branches.
Shared-prefix trieOne node per shared prefix; double borders mark complete words.bdmaaatddcurrentrootbdmbadamabatdadmad

double border complete word

wordsbat,dad,madquery.adterminalbat,dad,mad
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

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.
bat, dad, and mad share root but have separate first-letter branches. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does a matching prefix fail unless the final node is terminal?
Reference drawing

Problem trace

Wildcards try child alternatives; a complete match must end at a terminal node

Wildcards try child alternatives; a complete match must end at a terminal nodeLiterals follow matching trie edges. A dot tries each child for one character. Here a cannot satisfy the final d; e reaches bed. A full pattern matches only at a stored word's terminal node. Prefix ba exists but is not a word.Try child alternatives, then requirea terminal matchStored words: bake and bedb.dTry bothchildrenNeed d; onlyk existsbaekdeTerminal bed:trueba reaches a, but a has no word flag:false.The dot uses one character. Thesuffix still must match.
Execution trace
Input and goalStore words and support `.` as a wildcard that matches any one character.
Store three terminal pathsbat, dad, and mad share root but have separate first-letter branches.
Shared-prefix trieOne node per shared prefix; double borders mark complete words.bdmaaatddcurrentrootbdmbadamabatdadmad

double border complete word

wordsbat,dad,madquery.adterminalbat,dad,mad
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

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.
bat, dad, and mad share root but have separate first-letter branches. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does a matching prefix fail unless the final node is terminal?
Read it this way: Literals follow matching trie edges. A dot tries each child for one character. Here a cannot satisfy the final d; e reaches bed. A full pattern matches only at a stored word's terminal node. Prefix ba exists but is not a word. Why is the existing ba path insufficient while b.d reaches a stored word?

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.