Problem overview
The task is a WordDictionary type that stores words and finds them again, where the word you search for can contain dots. A dot matches exactly one letter. The type has three parts: Constructor returns an empty dictionary, AddWord(word string) adds a word, and Search(word string) bool says whether some added word matches. An added word matches when it has the same length and, at every position, the same letter, except that a dot in the search accepts any letter.
After adding "bad", "dad" and "mad", the search "pad" is false, "bad" is true, ".ad" is true (it matches all three words) and "b.." is true. Words added are 1 to 25 lowercase letters. A searched word has letters and at most 2 dots. There are at most 100,000 calls.
Adding a word should take O(L) time, where L is its length. 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.
Approach: a trie, with a branch at each dot
A trie stores each word as a path of letters from a root, with a flag on the node where a word ends. Words with the same beginning share the start of their path. Adding a word walks and extends that path.
Searching a word of plain letters is a walk down the path, and the word was added if the walk reaches a node whose end flag is set. A dot changes that, because the search can't know which child to take. It has to try all of them. That calls for recursion: a helper that answers does the rest of the word, from index i on, match a path that starts at this node? At a letter it follows the one matching child. At a dot it asks the same question of every child, and one match is enough.
Since a dot stands for exactly one letter, the match always consumes the word position by position. A word of length 3 can only match paths of 3 letters, and a dot never matches "no letter".
Step by step
- Build the node.
TrieNodehaschildren, amap[rune]*TrieNodefrom each next letter to its child, andisEnd, aboolthat marks where an added word ends.NewTrieNodereturns&TrieNode{children: make(map[rune]*TrieNode)}, because a map must be made before it can hold anything. - Give the dictionary a root.
WordDictionaryhas a fieldrootof type*TrieNode, andConstructorcreates it withNewTrieNode(). - Add a word. Walk from the root with a variable
node. For each letter, create the child ifnode.children[c]isnil, then move down. After the loop, setnode.isEnd = true. The flag is what makes the word count as added, and not just as the beginning of a longer word. - Search through a helper.
Searchreturnsthis.searchFrom(this.root, word, 0). - The helper's base case. When
i == len(word), every character has been matched, so the answer isnode.isEnd: a word has to end exactly here. - Read the current character as
c := rune(word[i]). Indexing a string gives a byte, andrune(...)converts it to the type of the map's keys. - At a dot, loop over every child and return
trueifsearchFromon that child withi + 1returnstrue. If no child leads to a match, returnfalse. - At a letter, return
falseifnode.children[c]isnil. Otherwise return the result ofsearchFromon that child withi + 1. A letter has only one way to go, so there is no loop.
The solution in Go
type TrieNode struct {
children map[rune]*TrieNode
isEnd bool
}
func NewTrieNode() *TrieNode {
return &TrieNode{children: make(map[rune]*TrieNode)}
}
type WordDictionary struct {
root *TrieNode
}
func Constructor() WordDictionary {
return WordDictionary{root: NewTrieNode()}
}
func (this *WordDictionary) AddWord(word string) {
node := this.root
for _, c := range word {
if node.children[c] == nil {
node.children[c] = NewTrieNode()
}
node = node.children[c]
}
node.isEnd = true
}
func (this *WordDictionary) Search(word string) bool {
return this.searchFrom(this.root, word, 0)
}
func (this *WordDictionary) searchFrom(node *TrieNode, word string, i int) bool {
if i == len(word) {
return node.isEnd
}
c := rune(word[i])
if c == '.' {
for _, child := range node.children {
if this.searchFrom(child, word, i + 1) {
return true
}
}
return false
}
if node.children[c] == nil {
return false
}
return this.searchFrom(node.children[c], word, i + 1)
}
With "a" and "ab" added, the searches ".", "a.", ".b" and ".." are true, and ".a" and "b" are false. For ".", the helper tries the only child of the root, a, and reaches the end of the word on a node whose flag is set, because "a" was added. For ".a", the dot goes to the child a, and that node has a child b but none named a, so the branch fails.
Go details
- Map iteration order is random.
range node.childrenvisits the children in a different order from run to run. That is fine here, because the helper returnstrueif any child matches, and the final answer doesn't depend on which one is tried first. rangeover a map gives key and value. The loop writes_, childto ignore the letter and keep the child node.- Bytes versus runes.
word[i]is abyte, whilefor _, c := range wordyieldsrunes. The map's keys are runes, so the helper converts withrune(word[i]). For lowercase letters and dots, both give the same numbers. - A missing key gives
nil. Readingnode.children[c]for a letter that isn't there returnsniland doesn't add anything, so searching never changes the dictionary. - A method as a helper.
searchFromstarts with a lowercase letter, so it is private to the package. It is a method on*WordDictionaryonly so that the recursive calls readthis.searchFrom; it doesn't use any field of the dictionary besides what it is given.
Complexity
AddWord: O(L). One step per letter, each a map lookup and possibly one node creation.
Search: O(L) without dots. One step per letter, with a single child to follow. With dots, each dot can branch into up to 26 children, one for each lowercase letter. With at most 2 dots, the work is bounded by roughly 26 * 26 * L steps, which is still a constant factor times L. Without that limit on dots, a pattern like "......" could visit a large part of the trie.
Space: O(N), where N is the total number of letters across the added words, at most one node per letter. The recursion adds O(L) frames.
Edge cases and common mistakes
- A dot never matches nothing. After adding
"at", the searches"at."and"a.."arefalse(they need three letters), and"."isfalse(it needs one). - A prefix is not a match.
"a"is the beginning of"at", butSearch("a")isfalse. A search has to match a whole word, which is why the base case returnsnode.isEndand nottrue. - A dot at the start or end.
".t"istrueafter adding"at". - An empty dictionary. Both
"."and"a"givefalse: the root has no children, so the dot's loop finds nothing. - Several dots. After adding
"abc", the patterns"a.c","..c","..."and".b."aretrue, while"...."(too long) and".bd"(wrong last letter) arefalse. - Returning after the first child at a dot. Writing
return this.searchFrom(child, ...)inside the loop would try only one child. The code returns only when a branch succeeds, and moves on otherwise. - Returning
trueat the end of the loop. When no child matched, the answer isfalse. - Treating the dot like a letter. Looking up
node.children['.']would never find anything, since only letters are stored.
Testing
- Add
"bad","dad","mad", then search"pad","bad",".ad","b..":false true true true. - Add
"a","ab", then search".","a.",".b",".a","..","b":true true true false true false. - Add
"at", then search"a","at.",".t","a..",".":false false true false false.
