Problem overview
A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each of its children adds one more letter to it. Words that begin the same way share the same path from the root, so a trie can answer questions about a word in time that depends only on the length of that word.
The task is a Trie type with three methods: Insert(word string) adds a word, Search(word string) bool says whether that exact word was inserted, and StartsWith(prefix string) bool says whether some inserted word begins with the prefix. A word counts as a prefix of itself. Words and prefixes are 1 to 30 lowercase letters, and there are at most 100,000 calls.
After inserting "apple", Search("apple") is true, Search("app") is false and StartsWith("app") is true. After inserting "app" as well, Search("app") becomes true. Each operation should take O(L) time, where L is the length of its argument.
Approach: one node per prefix
A list of words would make every search scan the list, and comparing strings costs time too. A trie replaces that with a walk. Start at the root, which stands for the empty prefix, and follow one child per letter. A word needs at most L steps to reach its node, however many words are stored.
A path in the trie doesn't say whether a word ends there. After inserting "apple", the nodes for "a", "ap", "app", "appl" and "apple" all exist, but only the last one ends a word. So each node carries a flag, isEnd, that is set where an inserted word finishes. This flag is the entire difference between Search and StartsWith:
Searchwalks the word and then returns the flag of the node it reached.StartsWithwalks the prefix and returnstrueif the walk didn't fall off the tree, because every node of a trie lies on the path of some inserted word.
Step by step
- Design the node.
TrieNodehaschildren, amap[rune]*TrieNodefrom each next letter to the child node, andisEnd, abool. Ranging over a string gives runes, so the keys are runes, and the values are pointers so that a walk follows the shared nodes and not copies. - Write
NewTrieNode. It returns&TrieNode{children: make(map[rune]*TrieNode)}. A map must be made before anything can be stored in it.isEndis left out and starts asfalse. - Give
Triearootof type*TrieNode, and letConstructorreturn aTriewith a fresh root. An empty trie is a root with no children. - Insert. Start
nodeat the root. For each lettercof the word, create the child ifnode.children[c]isnil, then move down to it. After the loop, setnode.isEnd = true. - Search. Walk the same way, but create nothing. If a child is missing, return
false. After the loop, returnnode.isEnd, because reaching the node isn't enough. - StartsWith. The same walk over the prefix, and the answer after the loop is simply
true.
The solution in Go
type TrieNode struct {
children map[rune]*TrieNode
isEnd bool
}
func NewTrieNode() *TrieNode {
return &TrieNode{children: make(map[rune]*TrieNode)}
}
type Trie struct {
root *TrieNode
}
func Constructor() Trie {
return Trie{root: NewTrieNode()}
}
func (this *Trie) Insert(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 *Trie) Search(word string) bool {
node := this.root
for _, c := range word {
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}
func (this *Trie) StartsWith(prefix string) bool {
node := this.root
for _, c := range prefix {
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return true
}
Inserting "apple" creates 5 nodes below the root. Inserting "app" afterwards creates none: the path exists, and only the flag on the node for "app" changes, which is what turns Search("app") from false to true. Inserting "apply" then adds one node, because it shares the path "appl" with "apple".
Go details
- A missing map key gives the zero value. For a map of pointers that is
nil, sonode.children[c] == nilmeans "no such child". Reading a missing key doesn't add it to the map, soSearchandStartsWithnever change the trie. Searching"zebra"in a trie that holds only"dog"leaves it with 3 nodes. - Runes as keys.
for _, c := range wordyields the index, which is skipped with_, andcas arune, an integer type that is a valid map key. - Pointer receivers. The methods use
*Trie, sot := Constructor()followed byt.Insert("a")works: Go takes the address oftfor you. - Always use
Constructor. ATriedeclared asvar z Triehas anilroot, and inserting into it panics. The constructor is what creates the root. - Struct literals with field names.
Trie{root: NewTrieNode()}names the field, so the code stays correct if more fields are added later. - The flag defaults to
false. Go gives every field its zero value, so a new node doesn't end a word untilInsertsays so.
Complexity
Time: O(L) per operation. Each of the three methods does one pass over its argument. Each step is a map lookup, which takes constant time on average, and possibly the creation of one node.
Space: O(N) in total, where N is the total number of letters across the inserted words. In the worst case, when words share nothing, each letter gets its own node. Shared prefixes cost nothing extra.
Edge cases and common mistakes
- A prefix that is not a word. After inserting
"car"and"cart",StartsWith("ca")istruebutSearch("ca")isfalse. - No word continues that way.
StartsWith("cat")isfalsebecause there is notchild under"ca". - Inserting a word twice. Inserting
"dog"twice changes nothing: the nodes exist and the flag is alreadytrue. In that trie,Search("dog")andStartsWith("dog")aretrue, whileSearch("do"),StartsWith("dogs")andSearch("dogs")arefalse. - Returning
truefromSearchwhen the walk succeeds. That makesSearch("app")true after inserting only"apple". The answer is the flag. - Forgetting to set the flag. Without
node.isEnd = true, no word would ever be found. - Not making the map. Writing to a
nilmap panics, so each node needsmakein its constructor. - Creating nodes while searching. Assigning a child inside
Searchwould make laterStartsWithcalls answertruefor words that were never inserted.
Testing
- Insert
"apple", thenSearch("apple"),Search("app"),StartsWith("app"), insert"app",Search("app"):true false true true. - Insert
"car","cart", thenStartsWith("ca"),Search("ca"),StartsWith("cat"),Search("cart"):true false false true. - Insert
"dog"twice, thenSearch("dog"),StartsWith("dog"),Search("do"),StartsWith("dogs"),Search("dogs"):true true false false false.
