Design Add and Search Words Data Structure
Medium
Topics
Design a data structure with addWord(word) and search(word). In search, a . can match any single letter. search returns whether any added word matches.
Example 1
Two operations: store a word, and ask whether a pattern matches one that was stored. A
. in the pattern stands for exactly one character, never a run of them, so a pattern only ever matches a stored word of the same length.Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["WordDictionary","addWord","addWord","addWord","search","search","search","search"], values = [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output: [null,null,null,null,false,true,true,true]
Constraints
- 1 <= word.length <= 25
- Added words are lowercase letters; search words may contain ".".
- At most 10^4 calls.
Editorial — intuition, approach, complexity and pitfalls
Intuition
This is a trie plus wildcard search. On a normal character you descend one child; on a . you must try every child (a DFS branch).
Approach
- Store words in a trie keyed by length and characters.
- addWord inserts normally.
- search walks the trie; at a "." it recurses into all children, succeeding if any branch reaches an end node.
Dry Run
addWord bad, dad, mad. The root now has three children: b, d, m.
search pad -> false no p child at the root, so it fails on the first letter
search bad -> true an ordinary walk
search .ad -> true the dot forks: try b, then d, then m
b -> a -> d, end set -> true, and the rest is skipped
search b.. -> true b, then dot over its only child a, then dot over d
answer null|null|null|null|false|true|true|true
The dot has to BRANCH, not advance. It tries every child of the current node and
succeeds if any subtree matches the remaining pattern, which is why search is
recursive while addWord is a plain loop.
Treat a dot as "skip this position" instead -- recursing on the same node with
i + 1 -- and both .ad and b.. return false. The pattern length stops lining up
with the depth reached, so nothing with a dot in it can ever match.
`any(...)` short-circuits, so .ad stops at the b branch here. The worst case is
still every node at that depth, which is where the 26^d factor in the complexity
comes from -- a pattern of all dots explores the whole trie to that depth.Complexity
- Time — O(26^d * L): wildcards can branch across 26 children at each dotted position.
- Space — O(total chars): the trie nodes.
Common Pitfalls
- A "." must try every child, not just skip a position.
Full Solution — all languages
class WordDictionary:
def __init__(self):
self.ch = {}
self.end = False
def addWord(self, word):
node = self
for c in word:
node = node.ch.setdefault(c, WordDictionary())
node.end = True
def search(self, word):
def dfs(node, i):
if i == len(word):
return node.end
c = word[i]
if c == ".":
return any(dfs(x, i + 1) for x in node.ch.values())
return c in node.ch and dfs(node.ch[c], i + 1)
return dfs(self, 0)import java.util.*;
class WordDictionary {
Map<Character, WordDictionary> ch = new HashMap<>();
boolean end = false;
public WordDictionary() {
}
public void addWord(String w) {
WordDictionary n = this;
for (char c : w.toCharArray()) {
n.ch.putIfAbsent(c, new WordDictionary());
n = n.ch.get(c);
}
n.end = true;
}
public boolean search(String w) {
return dfs(this, w, 0);
}
boolean dfs(WordDictionary n, String w, int i) {
if (i == w.length()) return n.end;
char c = w.charAt(i);
if (c == '.') {
for (WordDictionary x : n.ch.values()) if (dfs(x, w, i + 1)) return true;
return false;
}
return n.ch.containsKey(c) && dfs(n.ch.get(c), w, i + 1);
}
}#include <bits/stdc++.h>
using namespace std;
struct WordDictionary {
map<char, WordDictionary*> ch;
bool end = false;
WordDictionary() {
}
void addWord(string w) {
WordDictionary* n = this;
for (char c : w) {
if (!n->ch.count(c)) n->ch[c] = new WordDictionary();
n = n->ch[c];
}
n->end = true;
}
bool search(string w) {
function<bool(WordDictionary*, int)> dfs = [&](WordDictionary* n, int i) -> bool {
if (i == (int)w.size()) return n->end;
char c = w[i];
if (c == '.') {
for (auto& kv : n->ch) if (dfs(kv.second, i + 1)) return true;
return false;
}
return n->ch.count(c) && dfs(n->ch[c], i + 1);
};
return dfs(this, 0);
}
};class WordDictionary {
constructor() {
this.ch = {};
this.end = false;
}
addWord(w) {
let n = this;
for (const c of w) {
if (!n.ch[c]) n.ch[c] = new WordDictionary();
n = n.ch[c];
}
n.end = true;
}
search(w) {
const dfs = (n, i) => {
if (i === w.length) return n.end;
const c = w[i];
if (c === ".") return Object.values(n.ch).some(x => dfs(x, i + 1));
return n.ch[c] !== undefined && dfs(n.ch[c], i + 1);
};
return dfs(this, 0);
}
}