Problem overview
You implement a class WordDictionary that stores words and finds them again, where the searched word may contain dots. A dot matches exactly one letter, any letter. AddWord(string word) stores a word. Search(string word) returns true if some stored word matches: it must have the same length, the same letter at every position where word has a letter, and any letter where word has a dot.
After adding "bad", "dad" and "mad", Search("pad") is false, Search("bad") is true, Search(".ad") is true because it matches all three words, and Search("b..") is true. A dot never stands for "no letter": with only "at" stored, Search("at.") and Search(".") are false. A search must match a whole word, so Search("a") is false, even though "a" begins "at".
Added words have 1 to 25 lowercase letters, and searched words have at most 2 dots. AddWord should run in O(L) time, and a search without dots in O(L) too.
Approach: a trie, and a recursive walk that branches at dots
A trie suits this problem. It stores words letter by letter in a tree, with one node per prefix. Each TrieNode has a dictionary children that maps a letter to the next node, and a flag isEnd that marks where an added word ends. The flag is needed because the node for "app" exists after adding "apple", but only a word that was added as a whole should be found by a search.
Adding a word walks down from the root, creating any missing child, and sets isEnd on the last node.
Searching without dots is the same walk: follow the letters, and if a letter has no child, the answer is false. With dots, the walk can't know which child to take. A dot has to be tried against every child. That calls for recursion: a helper SearchFrom(node, word, i) answers the question "does the rest of word, from index i on, match some path that starts at node?"
- If
iequalsword.Length, every character is matched. The answer is whether a word ends exactly here:node.isEnd. - If the current character is a letter, there is one way to go: the child under that letter, or false if there is none.
- If it is a dot, try every child. One branch that matches is enough, so return
trueat the first success. If no child works, returnfalse.
Without dots, each step is a single dictionary lookup, so a search costs O(L). A dot multiplies the work by at most the number of children, at most 26 for lowercase letters. With at most two dots in a search, that stays small.
Some searches on a dictionary holding only "hello" give these results: "hello" true, "hell" false, "h.llo" true, "h.l.." true, "....." true, and "...." false, since the pattern is one letter too short.
Step by step
- Declare
childreninTrieNodeas apublic Dictionary<char, TrieNode>set to a new empty dictionary. - Declare
isEndas apublic boolset tofalse. - Declare
rootinWordDictionaryas a newTrieNode. It stands for the empty prefix. - In
AddWord, startnodeatrootand loop over the letters. Ifnode.childrenlacks the letter (ContainsKey), store a newTrieNodeunder it. Then move down to that child. - After the loop, set
node.isEnd = true. - Write
Searchas one line: return whatSearchFromsays forroot,wordand index 0. - In
SearchFrom, write the base case. Wheni == word.Length, returnnode.isEnd. - Read the current character with
char c = word[i]. - Handle a dot. If
c == '.', loop overnode.children.Values. IfSearchFrom(child, word, i + 1)is true, returntrue. After the loop, returnfalse: no child led to a match. - Handle a letter. If
node.childrenhas no keyc, returnfalse. Otherwise return the result ofSearchFromonnode.children[c]withi + 1. There is no loop, because a letter has only one way to go.
The solution in C#
class TrieNode {
public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
public bool isEnd = false;
}
class WordDictionary {
TrieNode root = new TrieNode();
public void AddWord(string word) {
TrieNode node = root;
foreach (char c in word) {
if (!node.children.ContainsKey(c)) {
node.children[c] = new TrieNode();
}
node = node.children[c];
}
node.isEnd = true;
}
public bool Search(string word) {
return SearchFrom(root, word, 0);
}
bool SearchFrom(TrieNode node, string word, int i) {
if (i == word.Length) {
return node.isEnd;
}
char c = word[i];
if (c == '.') {
foreach (TrieNode child in node.children.Values) {
if (SearchFrom(child, word, i + 1)) {
return true;
}
}
return false;
}
if (!node.children.ContainsKey(c)) {
return false;
}
return SearchFrom(node.children[c], word, i + 1);
}
}
The C# details worth knowing:
- Characters and strings use different quotes.
'.'is achar, andc == '.'compares two chars. Writingc == "."would not compile, because acharcan't be compared with astring. - A missing key throws.
node.children[c]throwsKeyNotFoundExceptionifcis absent, so the code checksContainsKeyfirst. Assigningnode.children[c] = ...adds the key without any check. Dictionary.Valuesis a collection of the stored nodes, which aforeachcan walk. The dictionary must not be changed during that loop. Search only reads it.- The helper is private.
SearchFromhas no access modifier, so it is private to the class, which is what you want for a helper.AddWordandSearcharepublicand PascalCase. Code ported from Java or Python often hasaddWord, which doesn't match these names. - The recursion is as deep as the word. At most 25 levels, so there is no risk to the call stack.
- Printing a
boolshowsTrueorFalsein C#, with capital letters.
Complexity
Time. AddWord is O(L), one dictionary operation per letter. A Search without dots is O(L) too. Each dot can branch into as many calls as the node has children, up to 26, so a search with d dots takes about O(26^d * L) in the worst case. The lesson limits searches to two dots, so this is bounded by a constant times L.
Space: O(N) for the trie, where N is the number of nodes created, at most the total length of all added words. The recursion adds at most L frames while a search runs.
Edge cases and common mistakes
- Empty dictionary.
Search("a")andSearch(".")are both false: the root has no children. - A dot needs a letter. With "at" stored,
"."is false because "at" has two letters, and"at."is false because it needs three. - Prefix only.
Search("a")is false when only "at" is stored. The base case returnsnode.isEnd, nottrue. - All dots.
".."matches any stored two-letter word. With "a" and "ab" stored it is true because of "ab", and"."is true because of "a". - Dots in different places. With "a" and "ab" stored,
"a."and".b"are true, while".a"is false because no stored word has "a" as its second letter. - Returning the result of the first child only. At a dot, the loop must continue to the next child when one branch fails. Returning that branch's result straight away would miss matches in later children.
- Treating
'.'as a stored letter. Words are added with letters only. A dot is only meaningful in a search.
Testing
- Add "bad", "dad", "mad", then search "pad", "bad", ".ad", "b.." to get false, true, true, true.
- Add "a" and "ab", then search ".", "a.", ".b", ".a", "..", "b" to get true, true, true, false, true, false.
- Add "at", then search "a", "at.", ".t", "a..", "." to get false, false, true, false, false.
- On an empty dictionary, search "a" and "." to get false and false.
- Add "hello", then search "hello", "hell", "h.llo", "h.l..", ".....", "...." to get true, false, true, true, true, false.
