Design Add and Search Words Data Structure (LeetCode 211): Solution and Explanation
Design a structure that stores words and answers searches, where a search pattern may contain '.' characters that stand for any single letter. A search succeeds only if some stored word matches the whole pattern.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest design keeps every word in a list and compares the pattern against each word of the same length, treating '.' as a match for anything. Each search then costs O(N × L) for N stored words of length L, which gets slow when there are many words and many searches. A hash set handles exact searches in O(L) but cannot handle wildcards without generating every possible replacement for each dot, which is up to 26 to the power of the number of dots.
A trie fits the problem much better. Words that share a prefix share a path from the root, so searching letter by letter walks one path and fails as soon as a letter is missing. For a normal letter there is only one child to follow, so an exact search is O(L) no matter how many words are stored.
The wildcard is handled with a small DFS. When the pattern has a '.', instead of following one child you try every child of the current node and succeed if any of them leads to a match of the rest of the pattern. A complete match also needs the final node to be marked as the end of a word; otherwise searching "ba" would wrongly succeed when only "bad" was added.
The reference implementation makes the WordDictionary object itself a trie node, with a children map and an isEnd flag, so adding a word just creates nested WordDictionary instances along the path.
Approach: Trie with DFS for wildcards
- Each node holds a
childrenmap from letter to node and anisEndflag, both empty or False initially. addWordwalks from the root, creating a child node for any missing letter, and setsisEnd = Trueon the last node.searchcalls a recursivedfs(node, i)starting from the root at index 0.- If
iequals the word length, returnnode.isEnd. - If
word[i]is '.', trydfs(child, i + 1)for every child and return True if any succeeds, otherwise False. - For a letter, return False if it is not a child, otherwise continue with
dfs(node.children[word[i]], i + 1).
Step-by-step example
addWord("bad"), addWord("dad"), addWord("mad"), then search("pad"), search("bad"), search(".ad"), search("b..")- The three adds create root children b, d and m, each followed by a and then d, with
isEndset on each final d. - search("pad") fails at the root because there is no child p, so it returns False.
- search("bad") follows b, a, d and finds
isEndTrue, so it returns True. - search(".ad") tries every root child. The first child, b, leads to a and then d with
isEndTrue, so it returns True without checking d or m. - search("b..") follows b, then the dot tries a, then the second dot tries d, which ends a word, so it returns True. The outputs are False, True, True, True.
Code: Python, Java, C++
1class WordDictionary:
2 def __init__(self):
3 self.children = {}
4 self.isEnd = False
5
6 def addWord(self, word: str) -> None:
7 node = self
8 for char in word:
9 if char not in node.children:
10 node.children[char] = WordDictionary()
11 node = node.children[char]
12 node.isEnd = True
13
14 def search(self, word: str) -> bool:
15 def dfs(node, i):
16 if i == len(word):
17 return node.isEnd
18 if word[i] == '.':
19 for child in node.children.values():
20 if dfs(child, i + 1):
21 return True
22 return False
23 if word[i] not in node.children:
24 return False
25 return dfs(node.children[word[i]], i + 1)
26
27 return dfs(self, 0)1class WordDictionary {
2 private Map<Character, WordDictionary> children;
3 private boolean isEnd;
4
5 public WordDictionary() {
6 children = new HashMap<>();
7 isEnd = false;
8 }
9
10 public void addWord(String word) {
11 WordDictionary node = this;
12 for (char c : word.toCharArray()) {
13 if (!node.children.containsKey(c)) {
14 node.children.put(c, new WordDictionary());
15 }
16 node = node.children.get(c);
17 }
18 node.isEnd = true;
19 }
20
21 public boolean search(String word) {
22 return dfs(this, word, 0);
23 }
24
25 private boolean dfs(WordDictionary node, String word, int i) {
26 if (i == word.length()) return node.isEnd;
27 char c = word.charAt(i);
28 if (c == '.') {
29 for (WordDictionary child : node.children.values()) {
30 if (dfs(child, word, i + 1)) return true;
31 }
32 return false;
33 }
34 if (!node.children.containsKey(c)) return false;
35 return dfs(node.children.get(c), word, i + 1);
36 }
37}1class WordDictionary {
2public:
3 unordered_map<char, WordDictionary*> children;
4 bool isEnd;
5
6 WordDictionary() {
7 isEnd = false;
8 }
9
10 void addWord(string word) {
11 WordDictionary* node = this;
12 for (char c : word) {
13 if (node->children.find(c) == node->children.end()) {
14 node->children[c] = new WordDictionary();
15 }
16 node = node->children[c];
17 }
18 node->isEnd = true;
19 }
20
21 bool search(string word) {
22 return dfs(this, word, 0);
23 }
24
25private:
26 bool dfs(WordDictionary* node, string& word, int i) {
27 if (i == word.size()) return node->isEnd;
28 char c = word[i];
29 if (c == '.') {
30 for (auto& [ch, child] : node->children) {
31 if (dfs(child, word, i + 1)) return true;
32 }
33 return false;
34 }
35 if (node->children.find(c) == node->children.end()) return false;
36 return dfs(node->children[c], word, i + 1);
37 }
38};Time and space complexity
O(L) add, O(26^d × L) search
Adding a word and searching without dots both take O(L) for a word of length L. Each dot can branch into up to 26 children, so a search with d dots can explore up to 26 to the d paths, though it is never more than the number of trie nodes.
O(T)
The trie stores one node per distinct prefix, so memory is proportional to T, the total number of characters across all added words. A search also uses O(L) recursion depth.
Other approaches
Bucket words by length (time O(N × L) search, space O(T))
Store words in a map from length to a list, and compare a pattern only against words of the same length. Simple and decent when words have varied lengths, but each search is linear in the bucket size.
Trie with fixed 26-child arrays (time O(L) add, O(26^d × L) search, space O(26 × T))
Use an array of 26 child pointers instead of a map. It is the common choice in Java and C++ for speed, at the cost of more memory per node.
Common mistakes
- Returning True when the path exists but the final node is not marked as the end of a word, so prefixes of added words match.
- Returning the result of the first child in the dot branch instead of checking all children, which misses matches under later children.
- Treating '.' as a literal character during
addWord; only searches contain wildcards. - Creating a new trie node class but forgetting to initialize
childrenper instance, so all nodes share one map in some languages.
Frequently asked questions
Why use a trie for add and search words?
A trie lets you walk a word letter by letter and stop at the first missing letter, and shared prefixes are stored once. Wildcards become a branch over the children of one node instead of a scan of every stored word.
How is '.' handled in the search?
When the current pattern character is a dot, the search tries every child of the current node with the rest of the pattern and returns True if any branch matches.
What is the time complexity of search with wildcards?
Without dots it is O(L). Each dot can branch into up to 26 children, so the worst case is about O(26^d × L) for d dots, bounded by the size of the trie.
How is this different from Implement Trie?
Implement Trie supports exact search and prefix checks only. This problem adds the dot wildcard, which requires a DFS that can explore several children at once.