Problem overview
The class WordDictionary stores words and finds them again. addWord(String word) adds a word made of lowercase letters. search(String word) returns true if some added word matches the query. A match needs the same length, and at every position either the same letter or a dot in the query, because a dot '.' matches any single letter. A dot never matches "no letter".
After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true and search("b..") is true. After adding only "at", search("a") is false because a search must match a whole word, search("at.") is false because the dot needs a third letter, and search(".t") is true.
A search with no dots should take O(L) time, like addWord. At a dot, it may have to try every child of the node it has reached.
Approach: a trie, and a recursive search that branches at dots
The words go into a trie: one node per prefix, each with a map from the next letter to a child node, and a flag isEnd on the node where an added word finishes. Adding a word walks down from the root, creating the missing nodes, and sets the flag on the last one.
Searching a plain word follows one path, because each letter leads to at most one child. A dot breaks this: it can be any letter, so the search can't know which child to take. It has to try them all, and one successful branch is enough.
That is a natural fit for recursion. The helper searchFrom(node, word, i) answers one question: does the rest of word, from index i on, match some path that starts at node? A letter makes one recursive call, and a dot makes one call per child. The search has at most two dots, so the number of branches stays small.
Step by step
- Build the node class.
TrieNodegetschildren, aMap<Character, TrieNode>set to a newHashMap, and aboolean isEndthat starts asfalse. The initial values mean that no constructor is needed. - Give
WordDictionaryaroot, a newTrieNode. It stands for the empty prefix. - Write
addWord. Startnodeatroot. For each letter ofword.toCharArray(), ifnode.childrenhas no key for it,puta new node there; then move down withnode = node.children.get(c). After the loop setnode.isEnd = true. The flag is what makes a word count as added instead of only being the start of a longer word. - Write
searchas a single line that returnssearchFrom(root, word, 0). - Base case of
searchFrom. Ifi == word.length(), every character has been matched, so returnnode.isEnd. Being on the right path isn't enough: some added word must end exactly here. - Read the current character into
char c = word.charAt(i). - Handle a dot. If
c == '.', loop overnode.children.values(), the child nodes. For eachchild, ifsearchFrom(child, word, i + 1)istrue, returntrueat once. After the loop, returnfalse: no child led to a match. - Handle a letter. If
node.childrenhas no keyc, returnfalse. Otherwise returnsearchFrom(node.children.get(c), word, i + 1). There is no loop here, since a letter has only one way to go.
The solution in Java
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isEnd = false;
}
class WordDictionary {
TrieNode root = new TrieNode();
public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.children.containsKey(c)) {
node.children.put(c, new TrieNode());
}
node = node.children.get(c);
}
node.isEnd = true;
}
public boolean search(String word) {
return searchFrom(root, word, 0);
}
boolean searchFrom(TrieNode node, String word, int i) {
if (i == word.length()) {
return node.isEnd;
}
char c = word.charAt(i);
if (c == '.') {
for (TrieNode child : node.children.values()) {
if (searchFrom(child, word, i + 1)) {
return true;
}
}
return false;
}
if (!node.children.containsKey(c)) {
return false;
}
return searchFrom(node.children.get(c), word, i + 1);
}
}
Java details worth understanding:
- Character literals use single quotes.
'.'is achar;"."would be aString. Comparingc == '.'compares twocharvalues, which is correct with==. - Map keys are
Characterobjects. Thecharcis boxed automatically forcontainsKey,putandget. values()gives the map's values, here the child nodes, so the dot branch loops over them without needing the letters. AHashMapgives no promise about the order, which doesn't matter because every child is tried.- Imports.
MapandHashMaplive injava.util, so a file of your own needsimport java.util.*;. - The helper has no
public. It is an internal detail, called only fromsearch.
Complexity
addWord: O(L) time for a word of length L, with one map operation per letter.
search without dots: O(L). Each level makes one recursive call.
search with dots: at a dot, the search branches into every child, up to 26 for lowercase letters. With at most two dots, that is at most 26 * 26 branches, each continuing for at most L levels, which is a constant factor on top of O(L). Without a limit on dots it could visit much of the trie.
Space: the trie holds at most one node per letter of the added words. The recursion adds O(L) stack frames.
Edge cases and common mistakes
- A prefix isn't a match. With only "at" added,
search("a")isfalse. The base case returnsnode.isEnd, nottrue. - A dot needs exactly one letter.
search("at.")andsearch("a..")arefalsewhen only "at" is added, andsearch(".")isfalsetoo. - A dot can match a letter that ends a word. With "a" and "ab" added,
search(".")istruebecause the node for "a" hasisEndset, whilesearch(".a")isfalse, since no added word has "a" as its second letter. - Returning after the first child at a dot. The search must try every child until one succeeds. Returning the result of only the first child would miss matches in the others.
- Forgetting
isEnd. Without it, "ba" would match after adding only "bad".
Testing
These results come from running the class:
- 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 "at", "an", then search "a.", "..":
true,true.
