Problem overview
The class WordDictionary stores words and finds them again, where the word being searched for may contain dots. A dot matches exactly one letter, any letter.
addWord(word)adds a word made of lowercase letters (1 to 25 of them).search(word)returnstrueif some added word matches. A match has the same length aswordand the same letter at every position, except wherewordhas a dot.
After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true, and search("b..") is true. A search must match a whole word and a dot can't stand for nothing: after adding only "at", the searches "a", "at.", "a.." and "." are all false, while ".t" is true. A search has at most two dots, and there are at most 100,000 calls in all.
Approach: a trie, with a branching search at dots
Storing the words in a list and comparing against each one on every search costs time proportional to the number of words. A trie shares the letters of words that begin alike, so a search follows the letters of the query down the tree instead.
The trie here is the one from a basic prefix-tree design: each node has a map children from a letter to the next node, and a flag isEnd that is true where an added word ends. The root stands for the empty prefix.
With no dots, a search follows a single path, one level per letter, and takes O(L) for a word of length L. A dot is different: it can match any child, so the search doesn't know which way to go. It tries them all, and one match is enough. That makes the search recursive. A helper, searchFrom, answers one question: does the rest of the word, from index i on, match a path that starts at this node?
- If
iis the length of the word, every letter has been matched. The answer is whether a word ends exactly at this node,isEnd. - If the current character is a dot, try
searchFromon every child withi + 1. Returntrueas soon as one succeeds, andfalseif none does. - Otherwise it is a letter. If there is no child for it, return
false. If there is, continue into that one child.
Because a word has at most two dots, the search can branch at most twice, so it stays cheap: at most 26 branches at each dot.
Step by step
- Define
TrieNodewithchildren, anunordered_map<char, TrieNode*>, andbool isEnd = false. - Create
rootin the class withnew TrieNode(). An empty dictionary is a root with no children. - In
addWord, walk down from the root with a pointernode, one letter at a time. If the current letter has no child (count(c)is 0), create one withnew TrieNode(). Then move to that child. - Mark the last node with
isEnd = true. Without the flag, a word would be indistinguishable from the beginning of a longer one. searchhands the work to the helper:searchFrom(root, word, 0), starting at the root and at index 0.- Base case. When
i == word.size(), returnnode->isEnd. - Read the current character into
c. - Handle a dot. Loop over every entry of
node->children. A range-basedforwithauto [letter, child]splits each entry into its key and its value. IfsearchFrom(child, word, i + 1)istrue, returntrue. - No child matched. After the loop, return
false. - Handle a letter. If
node->childrenhas no keyc, returnfalse. - Otherwise recurse on
node->children[c]withi + 1. A letter has only one way to go, so there is no loop.
The solution in C++
struct TrieNode {
unordered_map<char, TrieNode*> children;
bool isEnd = false;
};
class WordDictionary {
public:
TrieNode* root = new TrieNode();
void addWord(string word) {
TrieNode* node = root;
for (char c : word) {
if (!node->children.count(c)) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->isEnd = true;
}
bool search(string word) {
return searchFrom(root, word, 0);
}
bool searchFrom(TrieNode* node, const string& word, int i) {
if (i == word.size()) {
return node->isEnd;
}
char c = word[i];
if (c == '.') {
for (auto [letter, child] : node->children) {
if (searchFrom(child, word, i + 1)) {
return true;
}
}
return false;
}
if (!node->children.count(c)) {
return false;
}
return searchFrom(node->children[c], word, i + 1);
}
};
The C++ details worth a closer look:
- Structured bindings.
auto [letter, child]unpacks eachpair<const char, TrieNode*>of the map into two names. It needs C++17. The loop doesn't useletter, so some compilers warn about an unused variable; the code still works. Without structured bindings, the same loop isfor (auto& entry : node->children)andentry.second. const string&in the helper. The helper takes the word by reference, so the recursion doesn't copy the string at every level.constpromises it won't change it.searchtakes its parameter by value, and then passes that copy down.- Signed against unsigned.
i == word.size()compares anintwith the unsignedsize_t. Sinceiis never negative, the comparison is safe, though some compilers warn. countbefore[]. Readingchildren[c]on a missing key would insert a null entry into the map, and the next level would dereference it. Thecounttest keeps searches from changing the map.- Memory. The nodes made with
neware never deleted, so they live until the program ends. A long-lived program would add a destructor, or hold the children withunique_ptr. - Order of the map. An
unordered_mapvisits children in no particular order, but the dot branch only asks whether any child matches, so the order doesn't change the answer.
Complexity
Let L be the length of the word.
addWord: O(L). One step per letter, each an average O(1) map operation plus at most one allocation.
search without dots: O(L). The recursion follows one path, one call per letter.
search with dots: O(26^d * L) in the worst case, where d is the number of dots. A dot tries up to 26 children, and each branch continues for the rest of the word. With at most two dots that is at most 676 paths of up to 25 letters.
The recursion goes as deep as the word, at most 25 levels.
Space: O(total letters added). Each word adds at most one node per letter, and words with a common beginning share their nodes. The recursion's extra space is O(L).
Edge cases and common mistakes
- A word that is only a beginning. After adding
"at",search("a")isfalse, because the node forahas noisEnd. The base case returns the flag, nottrue. - A dot stands for exactly one letter.
search("at.")andsearch("a..")arefalseafter adding"at", because the search runs out of children before the word runs out of characters.search(".")isfalsetoo, because"at"has two letters. - Dot at the end or the start.
search(".t")istrueafter adding"at", andsearch("..")istrueafter adding"ab". - Several words of different lengths. After adding
"a"and"ab",search(".")matches the first andsearch("..")the second. A dot never matches a longer word, since the flag is checked only when the query ends. - A dot where no child leads to a match. After adding
"a"and"ab",search(".a")isfalse: the dot tries the node fora, which has a childbbut nota. - Returning
truefrom the first child of a dot. A dot has to try every child until one succeeds. Returning the first child's answer would miss matches that sit under another child. - Returning from the loop too early with
false. Thereturn falsebelongs after the loop, not inside it. - Treating the base case as success. When the query is used up, the node must also be marked as the end of an added word.
Testing
- 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. - Add
"bad","bat","cat", then search"ba.","..t","...",".a.","b.d","c..": alltrue.
