Problem overview
The class WordDictionary stores words and finds them again, where the word being searched may contain dots. A dot matches any one letter. It has two methods:
addWord(_ word: String)adds a word made of lowercase letters.search(_ word: String) -> Boolreturnstrueif some added word matches. An added word matches when it has the same length and, at every position, the same letter; where the search word has a dot, any letter matches.
After adding "bad", "dad" and "mad": search("pad") is false, search("bad") is true, search(".ad") is true (it matches all three) and search("b..") is true. A dot stands for exactly one letter, never for none: after adding "at", search("at.") and search("a..") are false, and search("a") is false too, because a search must match a whole word.
The statement asks for addWord in O(L) time, where L is the length of the word. A search without dots takes O(L) too; at a dot it may have to try every child of the node it has reached. Search words have at most two dots.
Approach: a trie, and a search that branches at dots
A trie stores words letter by letter: each node stands for a prefix, a map takes the next letter to the child node, and a flag marks the nodes where an added word ends. Words that start the same way share nodes.
Without dots, a search follows one child per letter and finishes by checking the flag, so it costs O(L). With a dot, the search can't know which child to follow, so it tries all of them and succeeds if any one leads to a match. That is a natural recursion: a helper searchFrom(node, word, i) answers whether the rest of word, from index i on, matches a path that starts at node.
- When
iequals the length of the word, every character is matched, and the answer is whether a word ends at this node. - When the character is a dot, try
searchFromon every child withi + 1, and answertrueas soon as one succeeds. - When it is a letter, follow the one child for that letter if it exists, and answer
falseif it doesn't.
The cost of a dot is bounded by the alphabet: a node has at most 26 children, and a search word has at most two dots, so a search tries at most about 26 × 26 branches beyond the plain path. That keeps each search fast.
Take the search ".ad" in a dictionary holding "bad", "dad" and "mad". The root has the children b, d and m. The dot tries the children until one works. From b, the letters a and d follow the path of "bad", and the flag is set there, so that branch answers true. The branches through d and m would answer true as well.
Step by step
- Give
TrieNodeits children:var children: [Character: TrieNode] = [:], a dictionary from each next letter to the child node. - Add the word-end flag:
var isEnd = false, which becomestrueon the node where an added word ends. - Give
WordDictionarya root:let root = TrieNode(), standing for the empty prefix. - In
addWord, start at the root withvar node = root, and loop over the characters ofword. - Create a missing child. If
node.children[c]isnil, store a newTrieNode()there. - Move down with
node = node.children[c]!. The!is safe because the child exists by now. - Mark the end. After the loop, set
node.isEnd = true. - Write
searchas one line. It returns whatsearchFromanswers forroot,Array(word)and index 0. A SwiftStringcan't be indexed with an integer, and an array ofCharactervalues can. - Start
searchFromwith the base case. Ifi == word.count, returnnode.isEnd: the whole word is matched, and what counts is whether an added word ends exactly here. - Read the current character into
let c = word[i]. - Branch on a dot. If
c == ".", any child can match, so the code tries them all. - Loop over
node.children.values, the child nodes. - Recurse into each child with
i + 1, and returntrueif the recursive call returnstrue. One matching branch is enough. - Return
falseafter the loop. No child led to a match. - Handle a letter. After the dot's
if,cis a letter, so ifnode.children[c]isnil, returnfalse. - Follow the single path. Otherwise return
searchFrom(node.children[c]!, word, i + 1). A letter has only one way to go, so there is no loop.
The solution in Swift
class TrieNode {
var children: [Character: TrieNode] = [:]
var isEnd = false
}
class WordDictionary {
let root = TrieNode()
func addWord(_ word: String) {
var node = root
for c in word {
if node.children[c] == nil {
node.children[c] = TrieNode()
}
node = node.children[c]!
}
node.isEnd = true
}
func search(_ word: String) -> Bool {
return searchFrom(root, Array(word), 0)
}
func searchFrom(_ node: TrieNode, _ word: [Character], _ i: Int) -> Bool {
if i == word.count {
return node.isEnd
}
let c = word[i]
if c == "." {
for child in node.children.values {
if searchFrom(child, word, i + 1) {
return true
}
}
return false
}
if node.children[c] == nil {
return false
}
return searchFrom(node.children[c]!, word, i + 1)
}
}
The Swift details worth a closer look:
- Strings and arrays.
Array(word)turns aStringinto a[Character], soword[i]works. It is done once insearch, and the array is passed down the recursion, so the conversion isn't repeated at each level. - Comparing a
Characterwith".". Inc == ".", Swift reads the literal as aCharacterbecausecis one, so the comparison compiles without conversion. - Dictionary lookups are optionals.
node.children[c]has the typeTrieNode?. The code checks fornilbefore it applies!, because forcing anilcrashes the program. children.values. It is a collection of the dictionary's values, the child nodes, without their letters. A dictionary has no defined order, so the children may be tried in any order. That doesn't change the answer, because the result istrueif any branch matches.- Classes are reference types. Passing a
TrieNodetosearchFrompasses a reference to the same node, not a copy, so the search is cheap, androotas aletstill lets its contents change. - Calling a method from another method.
searchcallssearchFromwithoutself., which Swift allows inside a class's methods.
Complexity
addWord: O(L). One dictionary lookup, and possibly one node creation, per letter.
search without dots: O(L). One child is followed per letter. Converting the word to an array is also O(L).
search with dots: each dot multiplies the work by at most the number of children, which is at most 26. With at most two dots, a search visits at most about 26 × 26 × L nodes. The depth of the recursion is at most L.
Space: O(N) for the trie, in the total number of letters over all added words, in the worst case. A search needs O(L) extra space for the array of characters and the recursion.
Edge cases and common mistakes
- A prefix is not a match. After adding "at",
search("a")isfalse: the path exists, but no word ends there. That is the job of theisEndcheck in the base case. - A dot never matches nothing.
search("at.")needs a three-letter word, so it isfalsewhen only "at" was added.search(".")isfalsethere as well, since "at" has two letters. The recursion only moves to a child when it matches one character, so lengths must agree. - A dot at the end of a longer search. With "a" and "ab" added,
search(".")istruebecause "a" ends at the first level,search("..")istruebecause of "ab", andsearch(".a")isfalsebecause no word has a second letter "a". - All dots. After adding "bad", "dad" and "mad",
search("...")istrueandsearch("....")isfalse. - Returning
trueas soon as the letters run out. That would make every prefix a match. The base case returnsnode.isEnd. - Returning the result of the first child only. In the dot branch, the code must return
trueonly when a child succeeds, and keep trying the others when one fails. Thereturn falsecomes after the loop. - Forgetting to advance
i. CallingsearchFrom(child, word, i)would match the same dot again and recurse without end.
Testing
- Added "bad", "dad", "mad":
search("pad"),search("bad"),search(".ad"),search("b..")givefalse,true,true,true. - Added "a", "ab":
search("."),search("a."),search(".b"),search(".a"),search(".."),search("b")givetrue,true,true,false,true,false. - Added "at":
search("a"),search("at."),search(".t"),search("a.."),search(".")givefalse,false,true,false,false. - Added "bad", "dad", "mad":
search("...")givestrueandsearch("....")givesfalse.
