Design Add and Search Words Data Structure
Medium · Tries
Jump to codeSupport adding lowercase words and searching patterns where a dot matches exactly one arbitrary letter. A search succeeds if any stored word matches the entire pattern.
Examples
Example 1
operations = ["addWord","addWord","addWord","search","search","search","search"] words = ["bad","dad","mad","pad","bad",".ad","b.."]
Output: [false,true,true,true]
Example 2
operations = ["addWord","search","search"] words = ["a",".","b"]
Output: [true,false]
Constraints
- 1 <= word.length <= 20
- 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,000 calls will be made to addWord and search.
Function contract
Implement WordDictionary with addWord(word) and search(pattern), where . matches exactly one letter. Each case starts a new dictionary. Only search calls produce output.
Need a hint?
A normal character chooses one edge; a wildcard may branch.
Real trie interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Design autocomplete with TrieGoogle
- Implement Prefix Match FilterDatadog
- Implement trie-based autocompletePinterest
Solution approach
Store words in a trie. Search recursively with a node and pattern index. For a letter follow its edge; for a dot try every child. At the pattern’s end, require an end-of-word marker. Return as soon as one branch succeeds.
Complexity
Insertion O(L); search visits up to all matching trie paths, exponential in wildcard count in the worst case. Space is trie size plus O(L) search stack.
Python reference solution
class WordDictionary:
def __init__(self):
self.root = {}
def addWord(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node['$'] = True
def search(self, word):
def match(node, index):
if index == len(word):
return '$' in node
char = word[index]
if char == '.':
return any(match(child, index + 1) for key, child in node.items() if key != '$')
return char in node and match(node[char], index + 1)
return match(self.root, 0)
JavaScript solution
class WordDictionary {
constructor() { this.root = {children: new Map(), end: false}; }
addWord(word) {
let node = this.root;
for (const c of word) {
if (!node.children.has(c)) node.children.set(c, {children: new Map(), end: false});
node = node.children.get(c);
}
node.end = true;
}
search(word) {
function match(node, index) {
if (index === word.length) return node.end;
const c = word[index];
if (c === '.') {
for (const child of node.children.values()) {
if (match(child, index + 1)) return true;
}
return false;
}
return node.children.has(c) && match(node.children.get(c), index + 1);
}
return match(this.root, 0);
}
}
Java solution
class WordDictionary {
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean end;
}
private final TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (node.children[i] == null) node.children[i] = new TrieNode();
node = node.children[i];
}
node.end = true;
}
public boolean search(String word) { return match(root, word, 0); }
private boolean match(TrieNode node, String word, int index) {
if (node == null) return false;
if (index == word.length()) return node.end;
char c = word.charAt(index);
if (c == '.') {
for (TrieNode child : node.children) {
if (match(child, word, index + 1)) return true;
}
return false;
}
return match(node.children[c - 'a'], word, index + 1);
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class WordDictionary {
struct TrieNode {
array<int, 26> children;
bool end = false;
TrieNode() { children.fill(-1); }
};
vector<TrieNode> nodes{1};
bool match(int node, const string& word, size_t index) {
if (node == -1) return false;
if (index == word.size()) return nodes[node].end;
if (word[index] == '.') {
for (int child : nodes[node].children) {
if (match(child, word, index + 1)) return true;
}
return false;
}
return match(nodes[node].children[word[index] - 'a'], word, index + 1);
}
public:
void addWord(string word) {
int node = 0;
for (char c : word) {
int i = c - 'a';
if (nodes[node].children[i] == -1) {
int next = nodes.size();
nodes.emplace_back();
nodes[node].children[i] = next;
}
node = nodes[node].children[i];
}
nodes[node].end = true;
}
bool search(string word) { return match(0, word, 0); }
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 10 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
"addWord",
"addWord",
"addWord",
"search",
"search",
"search",
"search"
],
[
"bad",
"dad",
"mad",
"pad",
"bad",
".ad",
"b.."
]
][ false, true, true, true ]
[
[
"addWord",
"search",
"search"
],
[
"a",
".",
"b"
]
][ true, false ]
[
[
"addWord",
"addWord",
"search"
],
[
"at",
"bat",
".at"
]
][ true ]
[
[
"addWord",
"search",
"search"
],
[
"abc",
"a.c",
"ab."
]
][ true, true ]
[
[
"addWord",
"search"
],
[
"abcd",
"ab..e"
]
][ false ]
Drafts are saved per language in this browser when storage is available.