CodeArchon

mediumTriesFacebookAmazon

Wildcard Word Vault

A password-recovery drawer stores admitted words; later queries probe entries using '.' as a universal joker slot.

Design a data structure supporting addWord(word) and search(word) where '.' matches any single character.

Choose approach

·
b
a
d
1/7
Narrationstep 1 of 7

addWord("bad") inserts along 3 edges.

1class WordDictionary:
2 def __init__(self): self.root = {}
3 def addWord(self, word):
4 n = self.root
5 for c in word: n = n.setdefault(c, {})
6 n['$'] = True
7 def search(self, word):
8 def dfs(n, i):
9 if not n: return False
10 if i == len(word): return n.get('$', False)
11 c = word[i]
12 if c == '.':
13 return any(k != '$' and dfs(n[k], i+1) for k in n)
14 return dfs(n.get(c), i+1)
15 return dfs(self.root, 0)
Variables
word=bad
nodes=4

How to think about it

  1. No wildcards -> plain trie walk, O(L).
  2. '.' triggers a branching DFS over all children at that level.
  3. Return true the moment any branch terminates on an `isEnd` node.

Edge cases to catch in interview

  • All '.' pattern -> depth-first scan limited to pattern length.
  • Pattern longer than any stored word -> early termination.

Examples

Example 1[true]
{"ops":[{"op":"addWord","word":"a"},{"op":"search","pattern":"."}]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed