LeetCode #211 Medium

Design Add and Search Words Data Structure

Design Add and Search Words Data Structure is LeetCode 211 (Medium). Build a WordDictionary class with two methods:

  • addWord(word) stores a word of lowercase letters.
  • search(word) returns true if any stored word matches word, where each . matches any one letter.

There are up to 10⁴ calls, words have at most 25 letters, and a search contains at most 2 dots, so a dot can only multiply the work by a bounded amount.

Constraints
  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consist of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 10⁴ calls will be made to addWord and search.
triedepth-first-searchdesign
Open on LeetCode ↗
02

Intuition

Store the words in a trie: one node per letter, so words that start the same way share a path. A plain search walks one path, letter by letter. The dot is the twist: it can stand for any letter, so the search cannot know which child to take.

  • Letter: follow the one child for that letter; if it is missing, this path fails.
  • Dot: try every child that exists, and succeed if any of them leads to a match. A failure below one child just means trying the next.
  • End of the pattern: it is a match only if a stored word ends at this node.

Trying a child and backing up when it fails is depth-first search, so search is a small recursive function.

How to spot this pattern

A dictionary of words with letter-by-letter lookups is a trie. A single-letter wildcard turns that lookup into a trie wildcard search: fixed letters follow one child, and a wildcard branches with DFS. Word Search II (212) uses the same trie with a grid in place of a pattern.

03

Approach

Try it first

Before reading on, insert bad, dad and mad into a trie by hand, then trace .ad. At which node does the search have to branch, and what should happen when a branch fails? Aim for O(m) per addWord.

1

Store each word in the trie

Each node has children (letter → node) and is_word. To add a word, walk from the root letter by letter, creating a child when it is missing, and set is_word = True on the last node. Words with a shared beginning reuse the same nodes.

2

Search with a recursive helper

dfs(node, i) answers one question: can the rest of the pattern, from index i, be matched starting at node? Start with dfs(root, 0). Passing an index instead of slicing the string avoids copying the rest of the pattern on every call.

3

Match one character

At index i:

  • a letter: if node has that child, return dfs(child, i + 1); otherwise return False;
  • a dot: call dfs(child, i + 1) for each existing child and return True as soon as one succeeds. Return False only after every child has failed.
4

Check the end of the pattern

When i == len(word), every character has been matched. Return node.is_word: the answer is true only if a stored word ends exactly at this node.

04

Code in Python, C++ and Java

▶1class TrieNode:
▶2 def __init__(self):
▶3 self.children = {}
▶4 self.is_word = False
▶5 
▶6class WordDictionary:
▶7 def __init__(self):
▶8 self.root = TrieNode()
▶9 
▶10 def addWord(self, word: str) -> None:
▶11 node = self.root
▶12 for ch in word:
▶13 if ch not in node.children:
▶14 node.children[ch] = TrieNode()
▶15 node = node.children[ch]
▶16 node.is_word = True
▶17 
▶18 def search(self, word: str) -> bool:
▶19 def dfs(node, i):
▶20 if i == len(word):
▶21 return node.is_word
▶22 ch = word[i]
▶23 if ch == ".":
▶24 for child in node.children.values():
▶25 if dfs(child, i + 1):
▶26 return True
▶27 return False
▶28 if ch not in node.children:
▶29 return False
▶30 return dfs(node.children[ch], i + 1)
▶31 
▶32 return dfs(self.root, 0)
rootbadword endsaddbadanswersnone yetadd bad · 3 new nodes
addWordbad
new nodes3nothing shared
Walk down from the root one letter at a time, creating each missing child (blue). The last node, d, gets the ring: a word ends there.
rootbaddadword endsadddadanswersnone yetadd dad · 3 new nodes
addWorddad
new nodes3nothing shared
Walk down from the root one letter at a time, creating each missing child (blue). The last node, d, gets the ring: a word ends there.
rootbaddadmadword endsaddmadanswersnone yetadd mad · 3 new nodes
addWordmad
new nodes3nothing shared
Walk down from the root one letter at a time, creating each missing child (blue). The last node, d, gets the ring: a word ends there.
rootbaddadmadword endssearchpadanswersfalseroot has no child p → false
i0
child pmissing
The root has no child p, so no stored word continues this way. This call returns false, so the answer is false.
rootbaddadmadword endssearchbadanswersfalseb → follow child b
i0
letterbone child to follow
b is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearchbadanswersfalsea → follow child a
i1
letteraone child to follow
a is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearchbadanswersfalsed → follow child d
i2
letterdone child to follow
d is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearchbadanswersfalsetruepattern used up · word ends here → true
i3end of the pattern
is_wordyes
Every character of bad is matched and this node has the ring, so a stored word ends exactly here: return true.
rootbaddadmadword endssearch.adanswersfalsetruedot → try b
i0a dot
try childb
A dot can be any letter, so try the children one by one. Start with b; if the rest of the pattern fails below it, come back and try the next child.
rootbaddadmadword endssearch.adanswersfalsetruea → follow child a
i1
letteraone child to follow
a is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearch.adanswersfalsetrued → follow child d
i2
letterdone child to follow
d is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearch.adanswersfalsetruetruepattern used up · word ends here → true
i3end of the pattern
is_wordyes
Every character of .ad is matched and this node has the ring, so a stored word ends exactly here: return true.
rootbaddadmadword endssearchb..answersfalsetruetrueb → follow child b
i0
letterbone child to follow
b is a plain letter, so there is exactly one child to follow. It exists, so move down to it and match the next character.
rootbaddadmadword endssearchb..answersfalsetruetruedot → try a
i1a dot
try childa
A dot can be any letter, so try the children one by one. Start with a; if the rest of the pattern fails below it, come back and try the next child.
rootbaddadmadword endssearchb..answersfalsetruetruedot → try d
i2a dot
try childd
A dot can be any letter, so try the children one by one. Start with d; if the rest of the pattern fails below it, come back and try the next child.
rootbaddadmadword endssearchb..answersfalsetruetruetruepattern used up · word ends here → true
i3end of the pattern
is_wordyes
Every character of b.. is matched and this node has the ring, so a stored word ends exactly here: return true.
05

Common pitfalls

Treating the wildcard as a literal key

✗ Wrong
node = node.children[ch]
✓ Right
for child in node.children.values():

A dot can be any letter, so the search must try every child. Looking up a child named . finds nothing, so .ad returns false even with bad stored.

Accepting any consumed path as a word

✗ Wrong
return True
✓ Right
return node.is_word

Reaching the end of the pattern only means its letters exist as a path. With only bad stored, ba reaches a node, but no word ends there, so the answer must be false.

Restarting after choosing a wildcard child

✗ Wrong
if dfs(self.root, i + 1):
✓ Right
if dfs(child, i + 1):

Once a dot picks a child, the rest of the pattern must continue below that child. Restarting at the root mixes letters from different words: with xy and b stored, .b wrongly returns true.

06

Edge cases

A pattern made only of dots, such as ...

It matches any stored word of exactly that length. A longer word passes through the node at depth 3, but that node is not a word end, so it does not count.

07

Complexity

Time
O(m) add, O(26² · m) search
Space
O(total letters added)
m is the word length. A search without dots follows one path. Each dot can fan out to at most 26 children and a search has at most 2 dots, so it explores at most 26² paths of length m. Without that limit, a pattern of all dots could visit the whole trie.
08

Design Add and Search Words Data Structure FAQ

Is this the same problem as Add and Search Word - Data structure design?

Yes. That was LeetCode's earlier title for problem 211. The problem, its examples and the trie solution are unchanged.

Why not keep the words in a list and compare each one?

It works: addWord appends, and search compares the pattern with every stored word of the same length, treating a dot as a match. But each search costs O(n · m) for n stored words, so 10⁴ calls can reach about 10⁸ letter comparisons. The trie only follows paths that match the pattern's letters.