211. Design Add and Search Words Data Structure
Asked at 12Apple35Amazon35Microsoft30Meta24Google22Bloomberg18Datadog87Snowflake59TikTok56Snap45Atlassian34Oracle27
Problem
Design WordDictionary with addWord(word) and search(word), where the search pattern may contain ., which matches any single letter.
Example: add "bad", "dad", "mad" → search("pad") = false, search(".ad") = true, search("b..") = true
Constraints: at most 2 dots per search; word length ≤ 25.
Trie + DFS: on ., try every child.
Complexity: add O(L); search O(26^dots · L) worst case.
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 k, child in node.items() if k != "$")
return ch in node and dfs(node[ch], i + 1)
return dfs(self.root, 0)
wd = WordDictionary()
for w in ("bad", "dad", "mad"):
wd.addWord(w)
assert not wd.search("pad") and wd.search("bad") and wd.search(".ad") and wd.search("b..")
assert wd.search("...") and not wd.search(".") and not wd.search("ba") and not wd.search("bad.")
class WordDictionary {
private static class Node { Node[] next = new Node[26]; boolean end; }
private final Node root = new Node();
public void addWord(String word) {
Node n = root;
for (char c : word.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.end = true;
}
public boolean search(String word) { return dfs(root, word, 0); }
private boolean dfs(Node n, String w, int i) {
if (i == w.length()) return n.end;
char c = w.charAt(i);
if (c == '.') {
for (Node child : n.next) if (child != null && dfs(child, w, i + 1)) return true;
return false;
}
Node child = n.next[c - 'a'];
return child != null && dfs(child, w, i + 1);
}
}
type WordDictionary struct {
children [26]*WordDictionary
end bool
}
func Constructor() WordDictionary {
return WordDictionary{}
}
func (this *WordDictionary) AddWord(word string) {
node := this
for i := 0; i < len(word); i++ {
c := word[i] - 'a'
if node.children[c] == nil {
node.children[c] = &WordDictionary{}
}
node = node.children[c]
}
node.end = true
}
func (this *WordDictionary) Search(word string) bool {
var dfs func(node *WordDictionary, i int) bool
dfs = func(node *WordDictionary, i int) bool {
if i == len(word) {
return node.end
}
if word[i] == '.' { // try every child
for _, child := range node.children {
if child != nil && dfs(child, i+1) {
return true
}
}
return false
}
child := node.children[word[i]-'a']
return child != nil && dfs(child, i+1)
}
return dfs(this, 0)
}