Problem overview
The task is to implement a class WordDictionary with two methods:
addWord(word)stores a word made of lowercase letters.search(word)returnstrueif some stored word matches. The searched word may contain dots, and a dot matches exactly one letter. A match must have the same length as the searched word and the same letter at every position that isn't a dot.
After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true because the dot matches the b, d or m, and search("b..") is true. A dot never matches zero letters: after adding only "at", search("at.") is false, and search("a") is false because a search matches a whole word, not the beginning of one.
addWord should take O(L) time for a word of length L. A search without dots takes O(L) too, and at a dot it may have to try every child of the node it has reached.
Approach: a trie, and a recursive search at dots
The words are stored in a trie, a tree with one node per prefix, where each node maps a letter to its child and has an isEnd flag that marks the end of a stored word. Adding a word walks down from the root, creating the missing nodes, and flags the last one.
Searching a word without dots follows one path: each letter has at most one child to go to. A dot breaks that, because the search can't know which child to take. It has to try every child, and one matching branch is enough. So the search becomes a recursion that remembers how far into the word it is:
- If every character has been matched, the answer is whether a stored word ends at the current node.
- If the current character is a letter, take that child if it exists, and continue from there.
- If it is a dot, try every child, and return
trueas soon as one of them leads to a match.
The statement allows at most two dots in a search, which keeps the branching small. Every added word is made of lowercase letters, so a node has at most 26 children.
Here is how many calls the helper makes on a dictionary holding "bad", "dad" and "mad":
| search | result | calls of searchFrom |
|---|---|---|
"pad" | false | 1 |
"bad" | true | 4 |
".ad" | true | 4 |
"b.." | true | 4 |
"pad" stops at once because the root has no child p. For ".ad", the dot tries the child b first, the rest "ad" matches below it, and the search returns true without looking at d or m.
Step by step
- Give
TrieNodean empty object forchildren. It maps each next letter to its child node. - Set
isEndtofalse. It becomestrueon the node where an added word ends. After adding"apple", the nodes for"app"and"apple"both exist, and only this flag tells them apart. - Create the root in the constructor. It stands for the empty prefix.
- In
addWord, startnodeat the root. - Loop over the letters of
wordwithfor...of. - Create a missing child: if
cis not a key ofnode.children, store a newTrieNodeunder it. - Move down to
node.children[c]. - Mark the end with
node.isEnd = trueafter the loop. - Make
searcha one-liner. It returnsthis.searchFrom(this.root, word, 0): start at the root, at index 0. - Write the base case of
searchFrom. Wheniequalsword.length, every character is matched, so returnnode.isEnd. Passing through a node isn't enough: a word must end exactly here. - Read the current character into a
constnamedc. - Check for a dot. A dot can match any child.
- Loop over the keys of
node.childrenwithfor...in. The child for a key isnode.children[key]. - Recurse into each child with the next index,
i + 1, and returntrueas soon as one call does. - After the loop, return
false. No child led to a match. - Handle a letter that has no child. If
cis not a key ofnode.children, returnfalse. - Otherwise follow the letter: return the result of
searchFromonnode.children[c]withi + 1. A letter has only one way to go, so there is no loop.
The solution in JavaScript
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class WordDictionary {
constructor() {
this.root = new TrieNode();
}
addWord(word) {
let node = 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) {
return this.searchFrom(this.root, word, 0);
}
searchFrom(node, word, i) {
if (i === word.length) {
return node.isEnd;
}
const c = 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);
}
}
The JavaScript details worth a closer look:
for...ofagainstfor...in.for (const c of word)goes over the characters of a string.for (const key in node.children)goes over the keys of an object, and each key is a string. Mixing them up is a common slip:for...inover a string gives its indexes, not its letters.word[i]reads one character of a string as a one-character string, so it can be compared with'.'using===.intests for a key.!(c in node.children)is true when no child exists forc. The parentheses matter, because!c in node.childrenwould negatecfirst.this.searchFrom. The recursive calls need thethis.prefix, becausesearchFromis a method of the class.- The return value is a boolean.
node.isEndistrueorfalse, and the other returns are literals, sosearchalways returns a boolean. - Early return from a loop. The
return trueinside the loop leaves the whole function, so the remaining children are not tried.
Complexity
addWord: O(L) time. One step per letter, with at most one node created per step.
search without dots: O(L) time. One recursive call per letter, and one more at the end.
search with dots: each dot can multiply the work by the number of children of the nodes it reaches, at most 26. With at most two dots the worst case is about 26 * 26 * L steps, which is still O(L) for a fixed alphabet and at most two dots. Without the limit on dots, the cost could grow much faster, as a trie with many words and many dots has many paths to try.
Space: O(N) for the trie, where N is the total number of letters in the added words, less where prefixes are shared. The search uses O(L) stack space for its recursion.
Edge cases and common mistakes
- A dot matches exactly one letter. After adding
"at",search("at.")andsearch("a..")are false, since they need three-letter words, andsearch(".")is false, since it needs a one-letter word. - A prefix is not a match. After adding
"at",search("a")is false. The base case returnsnode.isEnd, nottrue. - Words of different lengths. After adding
"a"and"ab":search(".")is true,search("..")is true, andsearch(".a")is false, because no added word hasaas its second letter. - An empty dictionary.
search(".")returnsfalse: the root has no children, so the dot has nothing to try. - Forgetting to return
falseafter the dot loop. The function would carry on and treat'.'as a letter, which isn't a key of any node. - Ignoring the result of the recursive call at a dot. Each call has to be tested with
if. Returning the first child's answer directly would give up on the other children. - Checking
isEndtoo early. The check belongs to the base case, after every character has been matched. - Adding a word with a dot. Only searches contain dots. A dot added to the trie would become a child like any other letter.
Testing
Results of the search calls, in order:
- Add
"bad","dad","mad", then search"pad","bad",".ad","b..":false true true true. - Add
"a","ab", then search".","a.",".b",".a","..","b":true true true false true false. - Add
"at", then search"a","at.",".t","a..",".":false false true false false. - Search
"."and"a"in an empty dictionary:false false.
