Problem overview
The class WordDictionary stores words and finds them again, where the word you search for can contain dots. A dot matches exactly one letter. It has two methods:
addWord(word)adds a word.search(word)returnstrueif some added word matches. A match has the same length and, at every position, the same letter, 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 stands for exactly one letter, never none, and a search must match a whole word: after adding "at", search("a") is false.
The statement asks for addWord in O(L) time, where L is the length of the word. A search without dots also takes O(L). At a dot it may have to try every child of the current node. A searched word has at most 2 dots.
Approach
Comparing the pattern with every stored word costs time proportional to the number of words. A trie stores words letter by letter, so words with a common start share a path, and a plain letter in the pattern leads to exactly one child.
The dot is the new part. A letter can only go one way, but a dot could be any letter, so the search has to try every child and see whether any of them leads to a match. That is a depth-first search, which a recursive helper does naturally: searchFrom(node, word, i) answers whether the part of word from index i on matches a path starting at node. With at most two dots, the branching stays small.
Step by step
- Write
TrieNode. It hasval children, aHashMap<Char, TrieNode>()from a letter to its child node, andvar isEnd,falseat first. The flag becomestrueon the node where an added word ends. After adding"apple", the node for"app"exists too, and only the flag says it is not a word. - Give
WordDictionarya root,val root = TrieNode(), the empty prefix. - In
addWord, walk down from the root. For each letter, if it is not innode.children, store a newTrieNode()under it. Then move into the child withnode.children[c]!!. After the loop, setnode.isEnd = true. - Make
searchcall the helper with the root, the word and index 0. - Write the base case of
searchFrom. Wheni == word.length, every character is matched, so returnnode.isEnd: the answer is whether an added word ends exactly here, not whether the search only passed through. - Read the current character into
val c = word[i]. - Handle a dot. If
c == '.', loop overnode.children.values, the child nodes. IfsearchFrom(child, word, i + 1)istruefor any of them, returntrue: the dot can match that child's letter, and one matching branch is enough. If no child leads to a match, returnfalse. - Handle a letter. If
cis not innode.children, returnfalse. Otherwise return the result of the recursive call onnode.children[c]!!withi + 1. There is no loop here, since a letter has only one way to go.
The solution in Kotlin
class TrieNode {
val children = HashMap<Char, TrieNode>()
var isEnd = false
}
class WordDictionary {
val root = TrieNode()
fun addWord(word: String) {
var node = root
for (c in word) {
if (c !in node.children) {
node.children[c] = TrieNode()
}
node = node.children[c]!!
}
node.isEnd = true
}
fun search(word: String): Boolean {
return searchFrom(root, word, 0)
}
fun searchFrom(node: TrieNode, word: String, i: Int): Boolean {
if (i == word.length) {
return node.isEnd
}
val c = word[i]
if (c == '.') {
for (child in node.children.values) {
if (searchFrom(child, word, i + 1)) {
return true
}
}
return false
}
if (c !in node.children) {
return false
}
return searchFrom(node.children[c]!!, word, i + 1)
}
}
Some Kotlin details in this code:
word[i]gives aChar, so a dot is written as the character literal'.'with single quotes, not as a string.node.children.valuesis the collection of the map's values, here the child nodes, sofor (child in node.children.values)visits every child.- The lookup
node.children[c]has the typeTrieNode?. The!!is safe because thec !in node.childrencheck before it already returned for a missing key. return falseinside the dot'sifcomes after the loop, so it runs only when no child matched. Areturn falseinside the loop would stop at the first child that fails.- The recursion goes one call deeper per letter, and the words have at most 25 letters, so the depth is small.
Following the second example
With "a" and "ab" added, these searches give:
"." -> true
"a." -> true
".b" -> true
".a" -> false
".." -> true
"b" -> false
The pattern "." tries the only child of the root, the node for a, and that node ends a word. ".a" fails because the node under a has only a b child. ".." needs a two-letter word, and "ab" is one.
Complexity
addWord: O(L). One map step per letter.
search: O(L) without dots. A letter moves along a single child. A dot tries every child, and a node has at most 26 children, because the letters are lowercase. With at most 2 dots, a search visits at most about 26 × 26 × L nodes, which is still bounded by a constant times L.
Space: O(N), with N the total number of letters in the added words. The recursion adds O(L) for the call stack.
Edge cases and common mistakes
- A dot never matches nothing. After adding
"at",search("at.")andsearch("a..")arefalse, since they need three letters. - A prefix is not a match.
search("a")isfalseafter adding only"at", because the node foradoesn't end a word. That is why the base case returnsnode.isEnd. - A pattern that is too long.
search("...")after adding only three-letter words works, andsearch("....")doesn't: the search runs out of children before it runs out of pattern. - Returning
falsetoo early at a dot. The result of one child must not decide the whole dot. Returntrueif any child matches, andfalseonly after trying all of them. - Dots in
addWord. Added words contain only letters. The dot is only a feature of searches.
Testing
addWord("bad") addWord("dad") addWord("mad")
search("pad") search("bad") search(".ad") search("b..") -> false true true true
addWord("at")
search("a") search("at.") search(".t") search("a..") search(".") -> false false true false false
