Design Add and Search Words Data Structure
Difficulty: Medium · Pattern: Tries · LeetCode #211
Design WordDictionary:
addWord(word): store a lowercase word,search(pattern):trueif any stored word matchespattern, where.matches any single letter.
Example
text
addWord("bad"); addWord("dad"); addWord("mad")
search("pad") → false; search("bad") → true; search(".ad") → true; search("b..") → trueHints
- Store words in a trie.
- For a normal letter, follow that child. For
., try every child, which means recursion/DFS.
Approach
Insertion is a standard trie insert. search is a DFS match(node, i): if i == len(pattern), return node.end. If pattern[i] is a letter, recurse into that child (if present). If it's ., recurse into each child and return true if any matches. Worst case (all dots) explores the whole trie, but typical queries are fast.
Complexity
Time: O(L) to add; search O(L) without dots, up to O(26^d · L) with d dots in the worst case. Space: O(total characters).
Python solution
class WordDictionary:
def __init__(self):
self.root = {}
def addWord(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["$"] = True
def search(self, word):
def match(node, i):
if i == len(word):
return "$" in node
ch = word[i]
if ch == ".":
return any(match(child, i + 1) for k, child in node.items() if k != "$")
return ch in node and match(node[ch], i + 1)
return match(self.root, 0)JavaScript solution
class WordDictionary {
constructor() { this.root = { c: {}, end: false }; }
addWord(word) {
let node = this.root;
for (const ch of word) node = node.c[ch] || (node.c[ch] = { c: {}, end: false });
node.end = true;
}
search(word) {
const match = (node, i) => {
if (i === word.length) return node.end;
const ch = word[i];
if (ch === '.') return Object.values(node.c).some((child) => match(child, i + 1));
return !!node.c[ch] && match(node.c[ch], i + 1);
};
return match(this.root, 0);
}
}