Problem overview
The lesson asks for a class WordDictionary that stores words and finds them again, where the word you search for may contain dots. A dot matches any one letter.
addWord(word)adds a word of lowercase letters and returns nothing.search(word)returnstrueif some added word matchesword. A match has the same length and, at every position, the same letter, except that a dot inwordaccepts any letter.
After adding "bad", "dad" and "mad", search("pad") is false, search("bad") is true, and search(".ad") and search("b..") are true. After adding "at", search("a") is false because a search must match a whole word, search(".t") is true, and search("at."), search("a..") and search(".") are false: a dot stands for exactly one letter, never for none.
The statement gives addWord a budget of O(L), where L is the length of the word. A search without dots takes O(L) too, and at a dot it may have to try every child of the node it has reached. A searched word has at most two dots.
Approach: a trie, and a search that branches at dots
A set of words would find an exact word quickly, but a dot would force it to compare against every stored word. A trie fits better. It is a tree with one node per prefix, in which each node maps a letter to the child node for that letter, and a flag isEnd marks a node where an added word ends. Words that start the same way share their first nodes.
Adding a word walks down from the root, creating the missing nodes along the way, and sets isEnd on the last one. This is the same as inserting into an ordinary trie, and it takes one step per letter.
Searching with letters only is a single walk: if a letter has no child, there is no match. A dot is where the walk has to choose, because the search cannot know which child to take. So it tries every child, and one branch that matches is enough.
This is a natural recursion. The helper searchFrom(node, word, i) answers one question: does the rest of word, from index i on, match a path that starts at node? Its cases are:
- If
iequals the length ofword, every character is matched, and the answer is whether a word ends exactly at this node. - If the character is a dot, try
searchFromon each child withi + 1, and answertrueas soon as one succeeds. - If the character is a letter, there is only one way to go: answer
falseif that child is missing, and otherwise recurse into it.
With at most two dots, the search tries at most 26 * 26 paths in addition to the straight walk, so it stays fast.
Step by step
- Write
TrieNode.val childrenis a new emptyscala.collection.mutable.Map[Char, TrieNode](), mapping each next letter to its child. - Add the flag.
var isEnd = falsebecomes true where an added word ends. - Create the root in
WordDictionary:val root = new TrieNode(). It stands for the empty prefix. addWordwalks down. It starts withvar node = rootand loops over each charactercofword.- Create what is missing. If
node.childrenhas no keyc, storenew TrieNode()under it. Thennode = node.children(c)moves down. - Mark the end. After the loop,
node.isEnd = true. searchdelegates. It returnssearchFrom(root, word, 0), starting at the root and at index 0.- The base case of
searchFrom. Wheni == word.length, returnnode.isEnd: the whole word is matched, so the question is whether an added word ends here, and not whether the search merely passed through. - Read the current character.
val c = word(i). - Handle a dot. If
c == '.', loop overnode.children.values, which are the child nodes. 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 returnsearchFrom(node.children(c), word, i + 1). One recursive call moves one level down, and no loop is needed.
The solution in Scala
class TrieNode {
val children = scala.collection.mutable.Map[Char, TrieNode]()
var isEnd = false
}
class WordDictionary {
val root = new TrieNode()
def addWord(word: String): Unit = {
var node = root
for (c <- word) {
if (!node.children.contains(c)) {
node.children(c) = new TrieNode()
}
node = node.children(c)
}
node.isEnd = true
}
def search(word: String): Boolean = {
return searchFrom(root, word, 0)
}
def searchFrom(node: TrieNode, word: String, i: Int): Boolean = {
if (i == word.length) {
return node.isEnd
}
val c = word(i)
if (c == '.') {
for (child <- node.children.values) {
if (searchFrom(child, word, i + 1)) {
return true
}
}
return false
}
if (!node.children.contains(c)) {
return false
}
return searchFrom(node.children(c), word, i + 1)
}
}
The Scala details worth a closer look:
- Characters use single quotes.
'.'is aChar, andword(i)is aChar, soc == '.'compares two characters. A string in double quotes would be a different type. children.values. On a map,valuesgives the stored values, here the child nodes, without their letters.- Missing keys.
node.children(c)throws aNoSuchElementExceptionwhencis not a key. Thecontainstest comes first, so the lookup is safe. returninside thefor. It leavessearchFromimmediately withtrue. Scala 3.5 compiles this with a warning about non-local returns and runs it as expected.- Recursive methods need a result type.
searchFromdeclares: Boolean, which Scala requires because the method calls itself.
Complexity
Time. addWord is O(L): one map lookup and at most one node creation per letter. A search without dots is O(L). A dot branches into every child, up to 26 of them, so with at most two dots a search visits at most about 26 * 26 * L nodes, which is still O(L) for a fixed alphabet. With more dots the worst case would grow quickly, up to every node of the trie.
Space. The trie holds at most one node per added letter, so O(T) for words with T letters in total. The recursion in search goes as deep as the searched word is long.
Edge cases and common mistakes
- A word that is only a prefix. After adding
"at",search("a")is false. The base case returnsisEndand nottrue. - A dot at the end. After adding
"cat","car"and"cab",search("ca.")is true andsearch("....")is false: there are no four-letter words. - A dot never matches nothing.
search("at.")is false after adding only"at": the dot needs a third letter, and the node for"at"has no children. - Only dots.
search("..")matches any two-letter word. After adding"a"and"ab"it is true, because of"ab", whilesearch(".")is true because of"a". - Different lengths. A word of the wrong length never matches, with or without dots, because the base case needs both the end of
wordand anisEndflag at the same time. - Returning after the first child. At a dot, returning
searchFrom's answer for the first child would miss matches under the other children. The loop returnstrueon a success and keeps trying on a failure. - An empty dictionary.
search(".")returns false, because the root has no children. - Skipping the
isEndtest. Returningtrueat the end of the word would make every prefix of an added word count as a word:search("ba")would be true after adding"bad".
Testing
- After
addWord("bad"),addWord("dad")andaddWord("mad"), searching"pad","bad",".ad"and"b.."givesfalse,true,true,true. - After
addWord("a")andaddWord("ab"), searching".","a.",".b",".a",".."and"b"givestrue,true,true,false,true,false. - After
addWord("at"), searching"a","at.",".t","a.."and"."givesfalse,false,true,false,false. - After adding
"cat","car"and"cab", searching"ca.","c.t","...","....",".."and"c.r"givestrue,true,true,false,false,true.
