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. Words that begin the same way share the same path from the root.
The class Trie has three methods:
insert(word)adds a word.search(word)returnstrueonly if exactly that word was inserted.startsWith(prefix)returnstrueif some inserted word starts withprefix. A word counts as a prefix of itself.
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.
The statement asks each operation to run in O(L) time, where L is the length of the word or prefix.
Approach
A list of words would need a scan of every word for each question. A hash set answers search quickly but can't answer startsWith without checking every word. A trie answers both by walking down from the root one letter at a time, so the time depends only on the length of the word asked about, not on how many words are stored.
Each node holds two things: a map from a letter to the child node for that letter, and a flag saying whether an inserted word ends at this node. The flag matters because after inserting "apple" the nodes for "app" and "apple" both exist, and only the flag tells which of them ends a word. That one flag is the whole difference between search and startsWith.
Step by step
- Write
TrieNode. Give itval children, aHashMap<Char, TrieNode>()that maps each next letter to its child, andvar isEnd, set tofalse. The map is in aval, so it is always the same map, although it can still grow. The flag is avarbecause it changes later. - Give
Triea root:val root = TrieNode(). The root stands for the empty prefix, so an empty trie is a root with no children. - In
insert, start at the root withvar node = rootand loop over the letters ofword. - Create missing paths. If a letter is not in
node.children(c !in node.children), store a newTrieNode()under it. - Move down with
node = node.children[c]!!. The child exists now, whether it was there before or was just created. - Mark the end. After the loop,
node.isEnd = trueturns the path into an inserted word. - In
search, follow the same walk but create nothing. If a letter has no child, returnfalse. After the loop returnnode.isEnd: reaching the node is not enough, because the path for"app"exists after inserting"apple". - In
startsWith, do the same walk and returntrueafter the loop. Every node of the trie lies on the path of some inserted word, so if every letter of the prefix had a child, some word starts with it.
The solution in Kotlin
class TrieNode {
val children = HashMap<Char, TrieNode>()
var isEnd = false
}
class Trie {
val root = TrieNode()
fun insert(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 {
var node = root
for (c in word) {
if (c !in node.children) {
return false
}
node = node.children[c]!!
}
return node.isEnd
}
fun startsWith(prefix: String): Boolean {
var node = root
for (c in prefix) {
if (c !in node.children) {
return false
}
node = node.children[c]!!
}
return true
}
}
Some Kotlin details in this code:
HashMapis available in Kotlin without an import, andHashMap<Char, TrieNode>()creates an empty one.c !in node.childrenchecks the map's keys, andinis the positive form. It reads better thancontainsKey.node.children[c] = TrieNode()stores a value under a key with index syntax.- Looking up a key,
node.children[c], has the typeTrieNode?, because the key might be missing: for an empty map,map['x']givesnull. The!!says it is notnullhere, and theifabove made sure of that.
Following the examples
For insert("car"), insert("cart"), then startsWith("ca"), search("ca"), startsWith("cat") and search("cart"), the results are:
[true, false, false, true]
"ca" is a path in the trie, so startsWith says true, but no word ends there, so search says false. There is no t child under "ca", so "cat" fails at its third letter.
Inserting "dog" twice changes nothing: the second walk finds every node already there and sets isEnd to true again. The trie then has a chain of three nodes below the root.
Complexity
Time: O(L) per operation, where L is the length of the word or prefix. Each letter costs one hash map lookup or insertion, which takes constant time on average.
Space: O(N), where N is the total number of letters in all inserted words, since each letter creates at most one node. Shared prefixes are stored once, so the real figure is often smaller.
Edge cases and common mistakes
- A word that is a prefix of another. With
"app"and"apple"both inserted, bothsearchcalls saytrue. TheisEndflag on the node for"app"is what allows it. - A prefix that is not a word. After
"apple"only,search("app")isfalseandstartsWith("app")istrue. - Inserting the same word twice. It is harmless.
- A prefix longer than any word. After
"dog", bothstartsWith("dogs")andsearch("dogs")arefalse: the walk fails at the fourth letter. - Returning
truefromsearchwithout the flag. That turnssearchintostartsWith. - Creating nodes while searching.
searchandstartsWithmust not add nodes, or a failed lookup would change the answers of later ones.
Testing
insert("apple") search("apple") search("app") startsWith("app") insert("app") search("app") -> true false true true
insert("car") insert("cart") startsWith("ca") search("ca") startsWith("cat") search("cart") -> true false false true
insert("dog") insert("dog") search("dog") startsWith("dog") search("do") startsWith("dogs") search("dogs") -> true true false false false
