Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
Build a class WordDictionary with:
addWord(word): store a lowercase word.search(word): returntrueif some stored word matches the query. The query is lowercase letters and., where.matches any one letter. Lengths must match exactly.
Words are up to 25 letters, queries have at most 2 dots, and there are up to 10⁴ calls.
Example:
addWord("bad"), addWord("dad"), addWord("mad")
search("pad") → false
search("bad") → true
search(".ad") → true (bad, dad or mad)
search("b..") → true (bad)Start with brute force
Keep a list of words. For each query, compare it with every word of the same length, position by position, treating . as a match. That's O(N · L) per search, where N is the number of stored words. With 10⁴ words and 10⁴ searches, that's up to 10⁸ word comparisons, each up to 25 characters.
A hash set handles queries with no dots in O(L). With dots you could expand every possibility: one dot is 26 lookups, two dots are 676. That's actually fast enough here, but it's brittle. More dots would explode, and interviewers want to see the trie idea.
Building the intuition
Start from Implement Trie (Prefix Tree). A query with no dots is just search there: walk one letter at a time.
Now picture the walk hitting a .. Which edge should it take? It doesn't know. Any of them might lead to a match. So try them all, one by one, and if any branch reaches a word ending, the answer is true.
"Try a branch, and if it fails, back up and try the next one" is depth-first search with recursion. Each call needs to know two things: which trie node we're at, and which character of the query we're matching next. So the function is dfs(node, i).
Why is this better than the brute force? The trie only has edges for letters that actually continue some stored word. A dot at a node with 2 children tries 2 branches, not 26. Dead ends are cut the moment a letter is missing.
The optimal approach
addWord is exactly the Trie's insert. For search:
- Define
dfs(node, i), meaning "can the query from positionionward be matched starting atnode?" - Base case: if
i == len(word), we've matched every character. Returnnode.is_end. - If
word[i]is a letter: look up that child. If it's missing, return false. Otherwise returndfs(child, i + 1). - If
word[i]is.: for every existing child, ifdfs(child, i + 1)is true, return true. If none work, return false. search(word)returnsdfs(root, 0).
The subtle detail is the base case. Reaching the end of the query isn't enough; a stored word must end exactly there. With only "bad" stored, search("ba") reaches a real node but must return false, because "ba" isn't a word.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # does a whole added word stop here?
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def search(self, word: str) -> bool:
def dfs(node: TrieNode, i: int) -> bool:
if i == len(word):
return node.is_end # used every letter: is a word ending here?
ch = word[i]
if ch == ".":
# A dot can be any letter, so try every branch that exists
for child in node.children.values():
if dfs(child, i + 1):
return True
return False
child = node.children.get(ch) # a real letter has only one way forward
return child is not None and dfs(child, i + 1)
return dfs(self.root, 0)struct TrieNode {
TrieNode* children[26] = {}; // children[c - 'a'], nullptr if no word continues with c
bool isEnd = false; // does a whole added word stop here?
};
class WordDictionary {
TrieNode* root;
bool dfs(TrieNode* node, const string& word, int i) {
if (i == (int)word.size()) {
return node->isEnd; // used every letter: is a word ending here?
}
char ch = word[i];
if (ch == '.') {
// A dot can be any letter, so try every branch that exists
for (TrieNode* child : node->children) {
if (child != nullptr && dfs(child, word, i + 1)) return true;
}
return false;
}
TrieNode* child = node->children[ch - 'a']; // a real letter has only one way forward
return child != nullptr && dfs(child, word, i + 1);
}
public:
WordDictionary() {
root = new TrieNode();
}
void addWord(string word) {
TrieNode* node = root;
for (char ch : word) {
int i = ch - 'a';
if (node->children[i] == nullptr) {
node->children[i] = new TrieNode();
}
node = node->children[i];
}
node->isEnd = true;
}
bool search(string word) {
return dfs(root, word, 0);
}
};class WordDictionary {
private static class TrieNode {
TrieNode[] children = new TrieNode[26]; // children[c - 'a'], null if no word continues with c
boolean isEnd = false; // does a whole added word stop here?
}
private final TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
public void addWord(String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int i = ch - 'a';
if (node.children[i] == null) {
node.children[i] = new TrieNode();
}
node = node.children[i];
}
node.isEnd = true;
}
public boolean search(String word) {
return dfs(root, word, 0);
}
private boolean dfs(TrieNode node, String word, int i) {
if (i == word.length()) {
return node.isEnd; // used every letter: is a word ending here?
}
char ch = word.charAt(i);
if (ch == '.') {
// A dot can be any letter, so try every branch that exists
for (TrieNode child : node.children) {
if (child != null && dfs(child, word, i + 1)) return true;
}
return false;
}
TrieNode child = node.children[ch - 'a']; // a real letter has only one way forward
return child != null && dfs(child, word, i + 1);
}
}class TrieNode {
constructor() {
this.children = new Map(); // letter -> TrieNode
this.isEnd = false; // does a whole added word stop here?
}
}
class WordDictionary {
constructor() {
this.root = new TrieNode();
}
/**
* @param {string} word
* @return {void}
*/
addWord(word) {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch);
}
node.isEnd = true;
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
const dfs = (node, i) => {
if (i === word.length) {
return node.isEnd; // used every letter: is a word ending here?
}
const ch = word[i];
if (ch === ".") {
// A dot can be any letter, so try every branch that exists
for (const child of node.children.values()) {
if (dfs(child, i + 1)) return true;
}
return false;
}
const child = node.children.get(ch); // a real letter has only one way forward
return child !== undefined && dfs(child, i + 1);
};
return dfs(this.root, 0);
}
}Dry run
Words bad, dad, mad. Query ".ad".
| Call | Char | Action | Result |
|---|---|---|---|
dfs(root, 0) | . | try children b, d, m in turn | — |
dfs(b, 1) | a | child a exists → go | — |
dfs(ba, 2) | d | child d exists → go | — |
dfs(bad, 3) | end | is_end of "bad" is true | true |
The first branch succeeds, so the search stops early and never visits d or m.
Query "b.d" with only bad stored: root → b (letter), then . tries the only child a, then d exists and ends a word → true. Query "b..": same path → true. Query "pad": root has no p child → false at once.
Complexity
addWord: O(L). One step per letter.search: O(L) with no dots. With dots, each dot can branch into up to 26 children, so the worst case is O(26^d · L) for d dots. With at most 2 dots, that's at most 676 paths of 25 letters. In practice it's far smaller, because the trie only has edges that exist.- Space: O(total letters added) for the trie, plus O(L) recursion depth during search.
Edge cases and traps
- Returning true at the end of the query without checking
is_end.search("ba")afteraddWord("bad")must be false. - A query longer than every word. The walk runs out of children and returns false. Don't index past the end of the query either; check
i == len(word)first. - Returning the first branch's answer for
.. Writingreturn dfs(child, i + 1)inside the loop returns after the first child, even when it fails. Return early only on true. - A query that is all dots, like
"...". It matches any word of length 3. The DFS handles it; it just explores more. - Searching an empty dictionary. The root has no children, so any query returns false.
Say it in the interview
"I'll store words in a trie, exactly like Implement Trie. Search becomes a DFS with two arguments, the trie node and the index in the query. A normal letter has one child to follow. A dot could be any letter, so I try every child that exists and return true if any branch works. At the end of the query I return the node's end flag, so prefixes don't count as words. Add is O(L). Search is O(L) without dots and grows with the number of dots, but the trie prunes every branch that no real word uses."
Follow-ups interviewers ask
- "What if there were many dots?" The worst case grows like 26^d. Two ideas help: group words by length first (a separate trie per length), and cache results for repeated queries.
- "Support
*meaning any number of letters?" At a*, try both "match zero letters" (dfs(node, i + 1)) and "consume one letter and stay on*" (dfs(child, i)for each child). It becomes glob matching. - "Why not a set with expansion?" It works for at most 2 dots (676 lookups), but it doesn't scale with more dots. The trie only explores letters that exist.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free