Problem
Implement a dictionary that can add a word and search for a word, where the search pattern may contain '.' to match any letter.
Original: LeetCode 211: Design Add and Search Words Data Structure.
Examples
Example 1
`WordDictionary: addWord("bad"), addWord("dad"), addWord("mad"), search("pad"), search("bad"), search(".ad"), search("b..")``[null, null, null, false, true, true, true]`Constraints
1 <= word.length <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsist of'.'or lowercase English letters.- There will be at most
2dots inwordforsearchqueries. - At most
10^4calls will be made toaddWordandsearch.
Hints
Hint 1
addWord stores a complete word. search may mix letters and dots, but it still has to match a stored word of the same length.
Hint 2
This is a trie plus DFS or recursion for the wildcard.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Keep a list of words and compare each pattern, treating '.' as a wildcard. That is linear in the number of stored words.
Optimal. A trie, with a recursive search that branches on '.'. If the alphabet is 26, a wildcard step costs a constant factor of 26 at that depth.
Alternative. You can also group words by length and scan only the words of the pattern's length, which is simple and sometimes fast enough.
Complexity
- Time
- O(L)
per addWord; search is O(L) without dots, worst case O(26^d · L)
- Space
- O(total characters stored in the trie)
Code
class WordDictionary:
def __init__(self) -> None:
self.root: dict = {}
def add_word(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(i: int, node: dict) -> bool:
if i == len(word):
return bool(node.get("#"))
ch = word[i]
if ch == ".":
return any(dfs(i + 1, child) for key, child in node.items() if key != "#")
return ch in node and dfs(i + 1, node[ch])
return dfs(0, self.root)
if __name__ == "__main__":
d = WordDictionary()
d.add_word("bad")
d.add_word("dad")
d.add_word("mad")
assert d.search("pad") is False
assert d.search("bad") is True
assert d.search(".ad") is True
assert d.search("b..") is True
print("ok")public class DesignAddAndSearchWordsDataStructure {
private static class Node {
final Node[] next = new Node[26];
boolean end;
}
private final Node root = new Node();
void addWord(String word) {
var cur = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (cur.next[c] == null) cur.next[c] = new Node();
cur = cur.next[c];
}
cur.end = true;
}
boolean search(String word) {
return dfs(word, 0, root);
}
private boolean dfs(String word, int i, Node node) {
if (node == null) return false;
if (i == word.length()) return node.end;
char ch = word.charAt(i);
if (ch == '.') {
for (var child : node.next) if (dfs(word, i + 1, child)) return true;
return false;
}
return dfs(word, i + 1, node.next[ch - 'a']);
}
public static void main(String[] args) {
var d = new DesignAddAndSearchWordsDataStructure();
d.addWord("bad");
d.addWord("dad");
d.addWord("mad");
if (d.search("pad") || !d.search("bad") || !d.search(".ad") || !d.search("b..")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: add "bad", "dad" and "mad"; search "pad" is false, "bad" is true, ".ad" is true, and "b.." is true.
- A pattern that is longer than every stored word should fail without going off a null child.
Follow-ups
- If there are many dots, you can start the DFS from the first literal letter, or keep a secondary index by length.
Interview script
"The dictionary is a trie. A letter follows one child, and a dot branches to every child. I only return true when the pattern is fully consumed on a word-ending node."
Source: LeetCode 211: Design Add and Search Words Data Structure