Problem overview
The class WordDictionary stores words and finds them again, where the word you search for may contain dots. A dot '.' matches any one letter.
addWord(word)adds a word made of lowercase letters.search(word)returnstrueif some added word matchesword. A match has the same length and, at every position, the same letter, except that a dot inwordaccepts any letter.
After adding "bad", "dad" and "mad", the search "pad" is false, "bad" is true, ".ad" is true (it matches all three words) and "b.." is true. A dot stands for exactly one letter, never for none, and a search must match a whole word: after adding "at", the search "a" is false.
Approach
Without dots, this is the trie of the previous kind of problem: a tree where each node is a prefix, each edge adds a letter, and a flag marks where an added word ends. Walking a word's letters from the root takes O(L) time for a word of length L.
A dot changes the search. At a normal letter there is one way to go, but at a dot the search cannot know which child leads to a match, so it must try every child of the current node. That calls for recursion: a helper follows one path, and at a dot it calls itself once per child. If any of those calls finds a match, the answer is true. The statement limits a search to at most two dots, so the number of paths to try stays small.
Step by step
- The node.
TrieNodehaschildren, of typeRecord<string, TrieNode>and starting as{}, which maps each next letter to its child, andisEnd, abooleanthat starts asfalseand becomestruewhere an added word ends. - The root.
WordDictionaryhas a fieldroot, a newTrieNode, the empty prefix. addWord. Start withnodeat the root. For each charactercof the word, create the child undercif it is missing (!(c in node.children)), then move down to it. After the loop, setnode.isEndtotrue. Marking it is what makes the word count as added and not just as the beginning of a longer one.search. It returns what the helper answers for the root, the word and the index 0:this.searchFrom(this.root, word, 0).- The helper's question.
searchFrom(node, word, i)asks: does the rest ofword, from indexion, match a path that starts atnode? - Base case. If
i === word.length, every character is matched, and the answer isnode.isEnd: whether an added word ends exactly here, not whether the search only passed through. - The current character.
cisword[i]. - A dot. If
c === '.', any child can match. Afor...inloop goes over the keys ofnode.children, and for eachkeythe helper is called onnode.children[key]with the next index,i + 1. If that call returnstrue, returntrue: one matching branch is enough. After the loop, returnfalse, because no child led to a match. - A letter. If
cis not a key ofnode.children, returnfalse. Otherwise return the helper's answer fornode.children[c]andi + 1. There is only one way to go, so there is no loop: one recursive call moves one level down.
The solution in TypeScript
class TrieNode {
children: Record<string, TrieNode> = {};
isEnd: boolean = false;
}
class WordDictionary {
root: TrieNode = new TrieNode();
addWord(word: string): void {
let node: TrieNode = this.root;
for (const c of word) {
if (!(c in node.children)) {
node.children[c] = new TrieNode();
}
node = node.children[c];
}
node.isEnd = true;
}
search(word: string): boolean {
return this.searchFrom(this.root, word, 0);
}
searchFrom(node: TrieNode, word: string, i: number): boolean {
if (i === word.length) {
return node.isEnd;
}
const c: string = word[i];
if (c === '.') {
for (const key in node.children) {
if (this.searchFrom(node.children[key], word, i + 1)) {
return true;
}
}
return false;
}
if (!(c in node.children)) {
return false;
}
return this.searchFrom(node.children[c], word, i + 1);
}
}
Details for TypeScript:
for...ofagainstfor...in.for (const c of word)goes over the characters of a string, whilefor (const key in node.children)goes over the keys of an object. The keys here are the letters that have a child. Mixing the two up is a common slip:for...inover a string gives its indexes, andfor...ofover a plain object is an error.word[i]reads the character at indexias a one-character string. Past the end it would beundefined, which is why the base case checksi === word.lengthfirst.- The type annotations are erased.
Record<string, TrieNode>andconst c: stringexist only for the compiler; at run timechildrenis a plain object. - The helper is a method. It is called as
this.searchFrom(...), like any method of the class.
Walking through an example
Take a dictionary with "bat" and "dad", and search for ".ad". The helper is called with the part of the word already matched, then |, then the rest, and each line shows the answer. The calls finish from the deepest one upward:
.a|d false
.|ad false
.ad| true
.a|d true
.|ad true
|.ad true
At the dot, the child b is tried first: "ba" exists, but "d" is not a child of it, so that branch returns false. The dot then tries d, which matches "dad" to the end, where isEnd is true. A single branch that matches is enough for the whole search to answer true.
Complexity
addWord: O(L) for a word of length L. search: without dots, O(L), since one path is followed. Each dot can branch into every child of its node, at most 26 of them, so with at most two dots the search tries at most 26 × 26 paths of length L, which is still O(L) when the number of dots is limited. Without that limit a search such as "......" could visit a large part of the trie. Space: O(total letters) for the nodes, plus O(L) for the call stack of a search.
Edge cases and common mistakes
- A dot never matches nothing. After
addWord("at"), the searches"at."and"a.."arefalse, because they need three-letter words, and"."isfalse, because it needs a one-letter word. - A whole word, not a prefix.
search("a")isfalsewhen only"at"was added. Returningtruewhen the word runs out, instead ofnode.isEnd, would wrongly accept it. - Words of different lengths. With
"a"and"ab"added,"."matches"a"and".."matches"ab"; the dot cannot jump to a word of another length. - A dot in the wrong place.
".a"isfalsewhen the second letter of every added word isb, even though the dot itself has a match. - Returning
falseafter the first child fails. The dot must try all children; only the loop ending without success givesfalse. - Missing the check for a letter that has no child. Reading
node.children[c]for a missing key givesundefined, and the next call would fail on it.
Testing
| Added words | Searches | Results |
|---|---|---|
"bad", "dad", "mad" | "pad", "bad", ".ad", "b.." | false, true, true, true |
"a", "ab" | ".", "a.", ".b", ".a", "..", "b" | true, true, true, false, true, false |
"at" | "a", "at.", ".t", "a..", "." | false, false, true, false, false |
"bad", "dad", "mad" | "...", "....", "b.d", "ba", "ban" | true, false, true, false, false |
