Problem overview
The class WordDictionary stores words and finds them again, and the word you search for may contain dots. A dot '.' matches exactly one letter, any letter. The class has two methods:
addWord(word)adds a word of lowercase letters.search(word)returnsTrueif some added word matches. A match has the same length as the search word and the same letter at every position, except that a dot matches any letter.
After adding "bad", "dad" and "mad": search("pad") is False, search("bad") is True, search(".ad") is True and search("b..") is True. A dot never stands for zero letters. After adding only "at", search("a") is False, because a search has to match a whole word, and search("at.") is False because it needs three letters. Search words contain at most two dots.
Approach: a trie, and a branch at every dot
A trie stores words letter by letter: each node has a children dictionary from a letter to the next node, and an isEnd flag that marks where an added word finishes. Words with the same beginning share nodes. Adding a word walks down from the root, creating missing nodes, and marks the last one with isEnd = True. That takes O(L) for a word of length L.
Searching a word with only letters is the same walk: follow each letter, give up if a child is missing, and at the end return isEnd, since the match must end exactly where an added word ends.
A dot is the new part. The search can't know which letter it stands for, so it tries every child of the current node. If any one of them leads to a match for the rest of the word, the search succeeds. That calls for a recursive helper, searchFrom(node, word, i), which answers one question: does word, from index i on, match a path that starts at node?
- If
iequalslen(word), every character is matched, and the answer isnode.isEnd. - If
word[i]is a letter, there is only one way to go: down that child if it exists, otherwiseFalse. - If
word[i]is a dot, try each child with indexi + 1and returnTrueas soon as one succeeds.
The cost grows with dots. A word without dots takes O(L). Each dot can multiply the work by at most the number of children of a node, 26 here, and a search has at most two dots, so the worst case is bounded by a constant times L.
Step by step
- Give
TrieNodeachildrendict that will map each next letter to its child node. - Add
isEnd, starting asFalse. It becomesTruewhere an added word ends. - Create the root in
WordDictionary.__init__:self.root = TrieNode(). - In
addWord, startnodeatself.root. - Loop over each character
cofword, going one level down per letter. - Create a missing child when
cis not innode.children. - Move down to
node.children[c]. - Mark the end with
node.isEnd = Trueafter the loop. - Let
searchdelegate. It returnsself.searchFrom(self.root, word, 0): start at the root, at index 0. - Write the base case of
searchFrom. Wheni == len(word), returnnode.isEnd. Passing through a word's node isn't enough, because the match must end where an added word ends. - Read the current character
c = word[i]. - Branch on a dot. If
c == '.', any child can match. - Loop over the child nodes with
node.children.values(). - Recurse on each child with
i + 1, and returnTrueas soon as one call does. One matching branch is enough. - Return
Falseafter the loop. No child led to a match. - Handle a letter. If
cis not innode.children, returnFalse. - Otherwise recurse into
node.children[c]withi + 1and return its answer. There is no loop, since a letter has one way to go.
The solution in Python
class TrieNode:
def __init__(self):
self.children = {}
self.isEnd = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isEnd = True
def search(self, word: str) -> bool:
return self.searchFrom(self.root, word, 0)
def searchFrom(self, node: TrieNode, word: str, i: int) -> bool:
if i == len(word):
return node.isEnd
c = word[i]
if c == '.':
for child in node.children.values():
if self.searchFrom(child, word, i + 1):
return True
return False
if c not in node.children:
return False
return self.searchFrom(node.children[c], word, i + 1)
Python details worth a closer look:
dict.values(). It gives the dictionary's values, which here are the child nodes, so the loop never needs the letters themselves. The dictionary isn't changed during the loop, so iterating it is safe.- Early return from inside a loop. The
return Truein the loop endssearchFromat once and passesTrueup through every caller. Thereturn Falsecomes after the loop, so it only runs when no child matched. - Calling the helper. The recursion goes through
self, as inself.searchFrom(...). A baresearchFrom(...)would raiseNameError. - A fresh dict per node.
self.children = {}is set in__init__, so every node has its own. A dict defined in the class body would be shared by all nodes. - Indexing and the base case.
word[i]would raiseIndexErrorati == len(word). The base case comes first for that reason.
Complexity
Time. addWord is O(L). A search without dots is O(L): one dictionary lookup per letter. At a dot, the search tries every child of the node, up to 26. With at most two dots, the number of paths the search follows is at most 26 × 26, and each path is at most L steps long. So a search is bounded by a constant times L, and the dots are the part that makes it slower than a plain trie lookup.
Space. The trie takes space for each distinct prefix of the added words, at most the total number of letters added. The recursion depth is at most L, at most 25 here.
Edge cases and common mistakes
- A dot needs exactly one letter. After adding
"at",search("at.")isFalseandsearch(".")isFalse, whilesearch(".t")isTrue. The dot has to consume a letter, so word length must agree. - A prefix isn't a match.
search("a")isFalseafter adding"at", because the node for"a"has noisEnd. That is why the base case returnsnode.isEndand notTrue. - Words of different lengths. After adding
"a"and"ab",search(".")isTruethrough"a",search("..")isTruethrough"ab", andsearch(".a")isFalse, since no added word hasasecond. - Every dot, not only the first. A dot in the middle, as in
"b.d", works the same way: the recursion carries on from the child it chose. - Dots only.
search("...")with"bad","dad"and"mad"added isTrue. - Searching an empty dictionary.
search(".")returnsFalse: the root has no children to try. - Returning inside the loop too early. Writing
return self.searchFrom(...)directly in the loop would return the first child's answer and never try the others. The code returns only when a child matches. - Treating a dot as a key.
addWordonly receives letters, so'.'is never a key inchildren. A dot in a search is handled by trying all children.
Testing
- Add
"bad","dad","mad"; thensearch("pad"),search("bad"),search(".ad"),search("b.."):False,True,True,True. - Add
"a","ab"; thensearch("."),search("a."),search(".b"),search(".a"),search(".."),search("b"):True,True,True,False,True,False. - Add
"at"; thensearch("a"),search("at."),search(".t"),search("a.."),search("."):False,False,True,False,False. - With nothing added,
search("a")andsearch("."):False,False.
