Home
DSA Patterns
Trie
Design Add and Search Words Data Structure
Design Add and Search Words Data Structure (LeetCode 211)
Design Add and Search Words Data Structure (LeetCode 211): store words in a trie and search them with '.' wildcards using a DFS that branches at every dot.
Problem Understanding
Design a WordDictionary with two operations:
addWord(word)stores a word.search(word)returnstrueif any stored word matches, where'.'in the pattern matches any one letter.
Example: after adding bad, dad and mad, search("pad") is false, search("bad") is true, search(".ad") is true and search("b..") is true.
The Intuition: A Trie, and a DFS for the Dots
addWord is the ordinary trie insert. The new part is search.
For a normal letter there is exactly one child to follow. For '.' there may be several, and you do not know which one leads to a match, so try them all: a DFS over (node, index).
- If
indexreaches the end of the pattern, return whether this node ends a word. - If the character is a letter, follow that child, or fail if it is missing.
- If it is
'.', try every child withindex + 1and returntrueas soon as one succeeds.
Design Add and Search Words Data Structure Visualization
GREEN = END OF A STORED WORD · . = ANY LETTER
ADD WORD
addWord
"bad"
Index
:
Returns
:
addWord("bad"): start at the root
Next
No 'b' child yet: create it and move down
Operations
Words are added first, then each search walks the trie. The branch being followed is outlined; at a '.', watch the search try one child, back up out of it if it fails, and move on to the next.
Design Add and Search Words Data Structure Dry Run
Stored: bat, bed. Search: b.d
| Index | Pattern | Node | Action |
|---|---|---|---|
| 0 | b |
root | follow b |
| 1 | . |
b |
try child a |
| 2 | d |
a |
no d child: back up |
| 1 | . |
b |
try child e |
| 2 | d |
e |
follow d |
| 3 | end | d |
ends a word: true |
Design Add and Search Words Data Structure LeetCode Solution
A trie with a DFS search that branches at every '.'.
Design Add and Search Words Data Structure Code
1class WordDictionary {2 constructor() {3 this.root = {};4 }56 addWord(word) {7 let node = this.root;8 for (const ch of word) {9 node = node[ch] ??= {};10 }11 node.$ = true;12 }1314 search(word) {15 const dfs = (node, i) => {16 if (i === word.length) return node.$ === true;17 const ch = word[i];18 if (ch === '.') {19 return Object.keys(node).some((key) => key !== '$' && dfs(node[key], i + 1));20 }21 return node[ch] !== undefined && dfs(node[ch], i + 1);22 };23 return dfs(this.root, 0);24 }25}
Design Add and Search Words Data Structure in Python, Java, C++, TypeScript and C
Design Add and Search Words Data Structure in Python
class WordDictionary:
def __init__(self):
self.root = {}
def addWord(self, word: str) -> None:
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node['$'] = True
def search(self, word: str) -> bool:
def dfs(node, i):
if i == len(word):
return '$' in node
ch = word[i]
if ch == '.':
return any(dfs(child, i + 1) for key, child in node.items() if key != '$')
return ch in node and dfs(node[ch], i + 1)
return dfs(self.root, 0)Design Add and Search Words Data Structure in Java
class WordDictionary {
private final TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
if (node.children[ch - 'a'] == null) node.children[ch - 'a'] = new TrieNode();
node = node.children[ch - 'a'];
}
node.isWord = true;
}
public boolean search(String word) {
return dfs(root, word, 0);
}
private boolean dfs(TrieNode node, String word, int i) {
if (i == word.length()) return node.isWord;
char ch = word.charAt(i);
if (ch == '.') {
for (TrieNode child : node.children) {
if (child != null && dfs(child, word, i + 1)) return true;
}
return false;
}
TrieNode next = node.children[ch - 'a'];
return next != null && dfs(next, word, i + 1);
}
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord;
}
}Design Add and Search Words Data Structure in C++
class WordDictionary {
struct TrieNode {
TrieNode* children[26] = {};
bool isWord = false;
};
TrieNode* root = new TrieNode();
bool dfs(TrieNode* node, const string& word, int i) {
if (i == (int)word.size()) return node->isWord;
char ch = word[i];
if (ch == '.') {
for (TrieNode* child : node->children) {
if (child && dfs(child, word, i + 1)) return true;
}
return false;
}
TrieNode* next = node->children[ch - 'a'];
return next && dfs(next, word, i + 1);
}
public:
void addWord(string word) {
TrieNode* node = root;
for (char ch : word) {
if (!node->children[ch - 'a']) node->children[ch - 'a'] = new TrieNode();
node = node->children[ch - 'a'];
}
node->isWord = true;
}
bool search(string word) {
return dfs(root, word, 0);
}
};Design Add and Search Words Data Structure in TypeScript
class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
class WordDictionary {
private root = new TrieNode();
addWord(word: string): void {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
node = node.children.get(ch)!;
}
node.isWord = true;
}
search(word: string): boolean {
const dfs = (node: TrieNode, i: number): boolean => {
if (i === word.length) return node.isWord;
const ch = word[i];
if (ch === '.') {
for (const child of node.children.values()) {
if (dfs(child, i + 1)) return true;
}
return false;
}
const next = node.children.get(ch);
return next !== undefined && dfs(next, i + 1);
};
return dfs(this.root, 0);
}
}Design Add and Search Words Data Structure in C
typedef struct WordDictionary {
struct WordDictionary* children[26];
bool isWord;
} WordDictionary;
WordDictionary* wordDictionaryCreate() {
return calloc(1, sizeof(WordDictionary));
}
void wordDictionaryAddWord(WordDictionary* obj, char* word) {
WordDictionary* node = obj;
for (; *word; word++) {
int c = *word - 'a';
if (!node->children[c]) node->children[c] = wordDictionaryCreate();
node = node->children[c];
}
node->isWord = true;
}
static bool dfs(WordDictionary* node, char* word) {
if (!*word) return node->isWord;
if (*word == '.') {
for (int c = 0; c < 26; c++) {
if (node->children[c] && dfs(node->children[c], word + 1)) return true;
}
return false;
}
WordDictionary* next = node->children[*word - 'a'];
return next && dfs(next, word + 1);
}
bool wordDictionarySearch(WordDictionary* obj, char* word) {
return dfs(obj, word);
}Edge Cases & Common Mistakes
- A prefix is not a word: with only
atstored,search("a")isfalse. Check the word-end flag at the end of the pattern, not just that the path exists. - Returning after the first child at a
'.': the first branch may fail while a later one matches; keep trying until one succeeds. - A pattern longer than every word: the walk runs out of children and fails; no special case is needed.
- All dots:
search("...")is true if any stored word has exactly three letters.
Summary
Add and Search Words is a trie plus one idea: a '.' is a branch point, so search becomes a DFS that tries each child there and backs up from dead ends. Letters follow a single child, and the end of the pattern checks the word-end flag.
More practice: DSA interview questions with answers · patterns cheat sheet
