Design Add and Search Words Data Structure
Implement a prefix tree that supports wildcard search with '.' using recursive depth-first search backtracking.
01The problem
Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary()Initializes the object.void addWord(word)Addswordto the data structure, it can be matched later.bool search(word)Returnstrueif there is any string in the data structure that matcheswordorfalseotherwise.wordmay contain dots'.'where dots can be matched with any letter.
02How to spot it
- Words are added dynamically and searched with literal characters and wildcard
'.'characters. - A regular character matches exactly one child node: follow
node.next[ch - 'a']. - A wildcard
'.'can match any letter from'a'to'z': branch across all existing children using depth-first search (DFS). - Combines Trie prefix tree storage with recursive backtracking.
03Pseudocode
match(w, i, node):
if i == len(w): return node.isWord
if w[i] != '.':
child = node.next[w[i]]
return child and match(w, i+1, child)
for each child of node:
if match(w, i+1, child): return true
return false04Watch it work
dictionary
initialized
Initialize WordDictionary Trie root. '.' wildcards match any child letter during DFS.
Pseudocode
- match(w, i, node):
- if i == len(w): return node.isWord
- if w[i] != '.':
- child = node.next[w[i]]
- return child and match(w, i+1, child)
- for each child of node:
- if match(w, i+1, child): return true
- return false
Variables
- storedWords
05Step-by-step dry run
addWord("bad"),addWord("dad"),addWord("mad"):- Root has children for
'b','d','m'. Each child leads to'a' -> 'd'withisWord = true.
- Root has children for
search("pad"):- Root has no child for
'p'-> returnsfalse.
- Root has no child for
search("bad"):- Direct match:
'b' -> 'a' -> 'd'exists andisWord == true-> returnstrue.
- Direct match:
search(".ad"):- First character is
'.': try all children of root ('b','d','m'). - Try child
'b': recursively search"ad"starting from node'b'. - Node
'b'has child'a', which has child'd'withisWord == true-> matches! - Returns
trueimmediately without needing to search'd'or'm'.
- First character is
search("b.."):- First character
'b': follow child'b'. - Second character
'.': try child'a'. - Third character
'.': try child'd'. Node'd'hasisWord == true-> returnstrue.
- First character
06Java solution
public class Main {
static class WordDictionary {
private final WordDictionary[] next = new WordDictionary[26];
private boolean isWord;
public WordDictionary() {}
public void addWord(String word) {
WordDictionary node = this;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (node.next[i] == null) {
node.next[i] = new WordDictionary();
}
node = node.next[i];
}
node.isWord = true;
}
public boolean search(String word) {
return match(word, 0, this);
}
private boolean match(String w, int i, WordDictionary node) {
if (i == w.length()) return node.isWord;
char ch = w.charAt(i);
if (ch != '.') {
WordDictionary child = node.next[ch - 'a'];
return child != null && match(w, i + 1, child);
}
for (WordDictionary child : node.next) {
if (child != null && match(w, i + 1, child)) {
return true;
}
}
return false;
}
}
public static void main(String[] args) {
WordDictionary dict = new WordDictionary();
dict.addWord("bad");
dict.addWord("dad");
dict.addWord("mad");
System.out.println(dict.search("pad"));
System.out.println(dict.search("bad"));
System.out.println(dict.search(".ad"));
System.out.println(dict.search("b.."));
}
}false true true true
07Why it works
Without wildcards, searching follows the single deterministic path dictated by the characters. When a dot '.' is encountered, it can match any character, so the algorithm branches across all non-null children. If any branch successfully completes the match (match(...) == true), the function short-circuits and returns true. If all children branches fail, it returns false.
08Time and space
- Time complexity:
addWord(word):O(L)whereLis word length.search(word):O(L)for queries without dots;O(26^d · L)in the worst case wheredis the number of dots in the pattern. With at most 2 dots,26^2 = 676branches, making search fast.
- Space complexity:
O(totalCharacters · 26)for the trie structure, plusO(L)recursion stack during search.
09Edge cases
- Search with all dots
"...": Explores words of length 3; returnstrueif any 3-letter word exists. - Dot at the end of word: Must verify that the terminal node has
isWord == true. - Pattern longer than any stored word: Reaches
nullchild; returnsfalse.
10Common mistakes
- Returning
trueon end of pattern without checkingisWord: Pattern".."matching prefix"ba"of"bad"would falsely returntrueifisWordis not checked. - Only searching the first child when encountering
'.': A dot must branch across all existing children until a match is found.
11Other approaches
- Group words by length: Maintain a map of word length to list of words, using regex or character comparison. Slower for large dictionaries, but prunes searches on mismatched word lengths.
12In the interview
- Point out the composition: Trie for prefix indexing plus DFS backtracking for wildcard branches.
- Highlight early exit: as soon as any child branch returns
true, returntrueimmediately without exploring remaining branches. - Note constraints: with at most 2 dots per search, exponential branch explosion is strictly bounded (
26^2 = 676).
13Quiz
What is the worst-case number of branches explored when searching a pattern with d dots?
- (Recommended) O(26^d)
- O(d^26)
- O(26 · d)
- O(d!)
Answer: O(26^d). Each dot can branch into up to 26 possible children, multiplying the search tree by 26 for each wildcard level.
14Solve it yourself
Open LeetCode #211 and submit the Trie + DFS solution.