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 the trie can say whether a word was added, or whether any added word starts a certain way, in time that depends only on the length of the word asked about.
The lesson asks for a class Trie with three methods:
insert(word)adds a word and returns nothing;search(word)returnstrueonly if exactly that word was inserted before;startsWith(prefix)returnstrueif some inserted word starts withprefix. A word counts as a prefix of itself.
After insert("apple"), search("apple") is true, but search("app") is false while startsWith("app") is true. After insert("app"), search("app") is true as well. After insert("car") and insert("cart"), startsWith("ca") is true, search("ca") is false and startsWith("cat") is false. Inserting "dog" twice changes nothing. Each operation should run in O(L) time, where L is the length of its word or prefix.
Approach: one node per prefix, one flag per word
Storing the words in a list or a set would answer search quickly, but startsWith would have to check every stored word. The trie answers both questions by walking down from the root, one letter per level.
Each node has two parts. The first is a map from a letter to the child node for that letter, and it contains only the letters that some word uses. The second is a flag, isEnd, which is true on a node where an inserted word ends. The flag is needed because after inserting "apple" the nodes for "app" and "apple" both exist, and only the flag tells you that "apple" was inserted and "app" was not.
The root stands for the empty prefix. An empty trie is a root with no children.
All three operations walk the same way. insert creates missing nodes along the path and sets the flag at the end. search and startsWith create nothing: they stop with false as soon as a letter has no child. They differ only at the end of the walk. search returns the node's isEnd flag, because reaching the node is not enough. startsWith returns true, because reaching the node proves that some inserted word passes through it: every node of a trie lies on the path of an inserted word.
Step by step
- Write
TrieNode.val childrenis a new emptyscala.collection.mutable.Map[Char, TrieNode](). Avalonly means thatchildrenalways refers to the same map, and a mutable map can still grow. - Add the flag.
var isEnd = falseis avarbecause it changes when a word ends here. - Create the root. Inside
Trie,val root = new TrieNode(). insertstarts at the root.var node = rootfollows the word down.- Loop over the letters.
for (c <- word)goes one level down per letter. - Create the missing child. If
node.childrenhas no keyc, storenew TrieNode()under it withnode.children(c) = new TrieNode(). This adds the entry to a mutable map. - Move down.
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 = true. This is what makes the whole word count as inserted. searchrepeats the walk. The samevar node = rootand loop, but a missing key returnsfalseand nothing is created.- Answer with the flag. After the loop,
return node.isEnd. startsWithrepeats the walk once more, with aprefixin place of the word. A missing key returnsfalse, and finishing the loop returnstrue.
The solution in Scala
class TrieNode {
val children = scala.collection.mutable.Map[Char, TrieNode]()
var isEnd = false
}
class Trie {
val root = new TrieNode()
def insert(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 = {
var node = root
for (c <- word) {
if (!node.children.contains(c)) {
return false
}
node = node.children(c)
}
return node.isEnd
}
def startsWith(prefix: String): Boolean = {
var node = root
for (c <- prefix) {
if (!node.children.contains(c)) {
return false
}
node = node.children(c)
}
return true
}
}
The Scala details worth a closer look:
containsbeforeapply.node.children(c)on a missing key throws aNoSuchElementException("key not found"). The code testscontainsfirst. The alternatives areget(c), which returns anOption(Nonefor a missing key), andgetOrElseUpdate(c, new TrieNode()), which would shorteninsertto one line.- Assignment syntax on a map.
node.children(c) = new TrieNode()is shorthand fornode.children.update(c, new TrieNode()). It adds the key or replaces its value. for (c <- word). AStringcan be looped over as a sequence ofChars, socis aChar, which matches the map's key type.returninside afor. It leaves the whole method, not only the loop. Scala 3.5 compiles this, prints a warning about non-local returns, and runs the code as expected, because the loop body is a function internally.valandvaron a node.nodeis avarbecause it moves down the trie, and the loop reassigns it.rootis avalbecause it never changes.new. The lesson writesnew TrieNode(). In Scala 3,TrieNode()works too.
Complexity
Time: O(L) per operation. Each of the three methods visits at most one node per letter of its argument, and a lookup or an insertion in the map of a node is constant on average.
Space. The trie holds at most one node per inserted letter, so after inserting words with a total of T letters it has at most T + 1 nodes, counting the root. Words that share a prefix share its nodes: after inserting "apple" and "app" the trie has 6 nodes, and after "car" and "cart" it has 5. search and startsWith use O(1) extra space.
Edge cases and common mistakes
- A prefix is not a word. After
insert("apple"),search("app")is false. A version that returnstrueafter reaching the node, without checkingisEnd, gets this wrong. - A word is a prefix of itself. After
insert("dog"),startsWith("dog")is true. - Longer than anything inserted. After
insert("dog"), bothstartsWith("dogs")andsearch("dogs")are false: the walk fails at the letters. - Inserting a word twice. The second insert finds every node present and sets the flag again, so nothing changes.
- Inserting a prefix later. After
insert("apple"),insert("app")creates no node. It only setsisEndon the existing node for"app". - Reading a missing key directly.
node.children(c)without thecontainstest throws an exception for a letter that no word uses. - The empty prefix.
startsWith("")returnstruewithout looking at any letter, even on an empty trie. The lesson's inputs are at least one letter long.
Testing
insert("apple"), thensearch("apple"),search("app"),startsWith("app")givetrue,false,true. Afterinsert("app"),search("app")givestrue.insert("car"),insert("cart"), thenstartsWith("ca"),search("ca"),startsWith("cat"),search("cart")givetrue,false,false,true.insert("dog")twice, thensearch("dog"),startsWith("dog"),search("do"),startsWith("dogs"),search("dogs")givetrue,true,false,false,false.
