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)returnstrueif any stored word matchesword, 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.
- 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.
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.
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.
Approach
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.
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.
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.
Match one character
At index i:
- a letter: if
nodehas that child, returndfs(child, i + 1); otherwise returnFalse; - a dot: call
dfs(child, i + 1)for each existing child and returnTrueas soon as one succeeds. ReturnFalseonly after every child has failed.
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.
Code in Python, C++ and Java
Common pitfalls
Treating the wildcard as a literal key
node = node.children[ch]
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
return True
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
if dfs(self.root, i + 1):
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.
Edge cases
...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.
Complexity
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.