Design Add and Search Words Data Structure
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Design a word dictionary that supports searching with wildcards.
Implement the class WordDictionary:
new WordDictionary()creates an empty dictionary.addWord(word)addsword.search(word)returnstrueif some added word matchesword.
Understand the problem
- A wildcard is a character that stands for "anything". Here it's the dot
., and it matches exactly one letter, any letter. - A word matches the search string if they have the same length and every non-dot letter is equal in the same position.
".ad"matches"bad","dad"and"mad"."b.."matches any 3-letter word starting withb. But".ad"does not match"ad"or"bead": lengths must be equal.
Example 1
ops: ["WordDictionary", "addWord", "addWord", "addWord", "search", "search", "search", "search"]
args: [[], ["bad"], ["dad"], ["mad"], ["pad"], ["bad"], [".ad"], ["b.."]]
expected: [null, null, null, null, false, true, true, true]search("pad")→false: never added.search("bad")→true: added.search(".ad")→true:"bad"matches (so do"dad"and"mad").search("b..")→true:"bad"matches.
How the tests work: each test is a sequence of calls. ops names each call (the first creates the object), args holds the arguments, and expected the return values.
Constraints
1 <= word.length <= 25- Added words contain lowercase English letters; search strings may also contain
.. - A search string has at most 2 dots.
- At most
10^4calls in total.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Store the words in a trie; search walks it letter by letter, and at a dot it tries every child and succeeds if any of them leads to a match.
The naive approach (and why it's slow)
Keep the words in a list. For each search, compare it with every word: same length, and every non-dot letter equal. That's O(number of words × length) per search: with 10,000 words and many searches, it adds up.
The key insight
Use the trie from Implement Trie. addWord is the same as insert, and a search with no dots is the same walk as search.
The only new thing is the dot. At a normal letter, there's exactly one child to follow. At a ., the letter could be anything, so the search branches: try every child, and if any branch matches, the answer is true.
match(node, i): "can word[i..] be found below node?"
i == word.length → node.isEnd (used every character: did a word end here?)
word[i] == '.' → true if ANY child c has match(c, i + 1)
otherwise → follow the child for word[i]; false if it doesn't existThis is a depth-first search (DFS) that only spreads out at dots. Every real letter follows a single path, so most of the trie is never visited.
Step by step
After adding bad, dad, mad, the trie's root has three children: b, d, m, and each continues with a then d (an end).
Search ".ad":
| Position | Character | At node | What happens |
|---|---|---|---|
| 0 | . | root | try each child: b first |
| 1 | a | b | follow a |
| 2 | d | b → a | follow d |
| 3 | (end) | b → a → d | isEnd is true → match! |
The first branch already matched, so we return true without trying d or m.
The code
The reference solution is below, with comments on every important line.
How fast is it?
With L = word length and d = number of dots:
addWord: O(L).search: O(L) with no dots. Each dot can branch into up to 26 children, so the worst case is about O(26^d · L). With at most 2 dots, that's still small.- Memory: O(total letters added).
Common mistakes
- Returning
truewhen the path exists but no word ends there. At the end, checkisEnd. - Returning the result of the first child at a dot. If the first child fails, you must try the others. Return
falseonly after all children fail. - Letting a dot match "zero letters" or several letters. It matches exactly one.
Going deeper
This is the trie's real superpower: a prefix-guided search that prunes everything not matching so far. The same idea, a DFS moving through a trie and another structure at the same time, is the heart of Word Search II.
Reference solution
class TrieNode {
children = new Map() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class WordDictionary {
root = new TrieNode()
/**
* @param {string} word
* @return {void}
*/
// Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
addWord(word) {
let node = this.root
for (const char of word) {
if (!node.children.has(char)) node.children.set(char, new TrieNode())
node = node.children.get(char)
}
node.isEnd = true
}
/**
* @param {string} word
* @return {boolean}
*/
search(word) {
// Can word[i..] be found starting below this node?
const match = (node, i) => {
// Used every character: it's a match only if a word ends right here.
if (i === word.length) return node.isEnd
if (word[i] === '.') {
// A dot can be ANY letter: try every child, succeed if any branch matches.
for (const child of node.children.values()) {
if (match(child, i + 1)) return true
}
return false
}
// A normal letter: there's only one way to go.
const child = node.children.get(word[i])
return child !== undefined && match(child, i + 1)
}
return match(this.root, 0)
}
}class TrieNode {
children = new Map<string, TrieNode>() // letter → next node
isEnd = false // does a whole word end at this node?
}
export default class WordDictionary {
private root = new TrieNode()
// Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
addWord(word: string): void {
let node = this.root
for (const char of word) {
let child = node.children.get(char)
if (!child) {
child = new TrieNode()
node.children.set(char, child)
}
node = child
}
node.isEnd = true
}
search(word: string): boolean {
// Can word[i..] be found starting below this node?
const match = (node: TrieNode, i: number): boolean => {
// Used every character: it's a match only if a word ends right here.
if (i === word.length) return node.isEnd
if (word[i] === '.') {
// A dot can be ANY letter: try every child, succeed if any branch matches.
for (const child of node.children.values()) {
if (match(child, i + 1)) return true
}
return false
}
// A normal letter: there's only one way to go.
const child = node.children.get(word[i])
return child !== undefined && match(child, i + 1)
}
return match(this.root, 0)
}
}class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {} # letter → next node
self.is_end = False # does a whole word end at this node?
class WordDictionary:
def __init__(self):
self.root = TrieNode()
# Exactly Trie.insert: follow the letters, creating nodes as needed, then mark the end.
def add_word(self, word: str) -> None:
node = self.root
for char in word:
node = node.children.setdefault(char, TrieNode())
node.is_end = True
def search(self, word: str) -> bool:
# Can word[i:] be found starting below this node?
def match(node: TrieNode, i: int) -> bool:
# Used every character: it's a match only if a word ends right here.
if i == len(word):
return node.is_end
if word[i] == ".":
# A dot can be ANY letter: try every child, succeed if any branch matches.
return any(match(child, i + 1) for child in node.children.values())
# A normal letter: there's only one way to go.
child = node.children.get(word[i])
return child is not None and match(child, i + 1)
return match(self.root, 0)