Problem overview
A trie, or prefix tree, stores words letter by letter in a tree. Each node stands for a prefix, and each child adds one more letter to it. Words that begin the same way share the same path from the root.
The task is to implement a class Trie with three methods:
insert(word)adds a word.search(word)returnstrueonly if that exact word was inserted before.startsWith(prefix)returnstrueif some inserted word begins withprefix. A word counts as a prefix of itself.
After insert("apple"), search("apple") is true, search("app") is false, and startsWith("app") is true. After insert("app") too, search("app") becomes true. Inserting the same word twice changes nothing. Each operation should run in O(L) time, where L is the length of the word or prefix.
Approach: a node per prefix, a flag per word
Storing the words in an array and scanning it would make every question cost time proportional to the number of words. A trie makes it depend only on the length of the word asked about: to follow a word, you step down one level per letter.
Each TrieNode holds two things:
children, an object that maps a letter to the child node for that letter. It only holds the letters that some word actually continues with.isEnd, a flag that istruewhen an inserted word ends at this node.
The flag is needed because the nodes can't tell the difference by themselves. After inserting "apple", the nodes for "app" and "apple" both exist, but only the second one ends a word.
After inserting "car", "cart" and "cat", the root has one child, c. That node has one child, a, which has two children, r and t. The r node has isEnd set to true and also a child t, so "car" is a word and a prefix of "cart". The node for "ca" has isEnd set to false.
The three operations differ only in what they do while walking down and what they return at the end:
insertcreates any missing node on the way, then setsisEndon the last one.searchfails if a node is missing, and otherwise returns the last node'sisEnd.startsWithfails if a node is missing, and otherwise returnstrue.
Step by step
- Give
TrieNodean empty object forchildren. It works as a map from a letter to a node and finds the child for a letter in one step. - Set
isEndtofalse. It becomestruewhere an inserted word ends. - Create the root in the
Trieconstructor. It stands for the empty prefix, so an empty trie is a root with no children. - In
insert, startnodeat the root. The walk always begins there. - Loop over the letters of
wordwithfor...of. Each letter goes one level down. - Create a missing child. If
cis not a key ofnode.children, store a newTrieNodeunder it. - Move down to
node.children[c], which exists now whether it was already there or was just created. - Mark the end. After the loop,
nodeis the node of the whole word, andisEnd = truemakes the word count as inserted. - In
search, start at the root and follow the letters, creating nothing. - Loop over the letters of
word. - Return
falsewhen a letter has no child, since no inserted word continues that way. - Move down to the child.
- Return
node.isEnd. Reaching the node isn't enough, because the path for"app"exists after inserting"apple"while no word ends there. - In
startsWith, start at the root and do the same walk overprefix. - Loop over the letters of
prefix. - Return
falseon a missing child: no word starts with this prefix. - Move down to the child.
- Return
true. Every node of the trie lies on the path of some inserted word, so if the whole prefix could be followed, a word starting with it exists.
The solution in JavaScript
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (const c of word) {
if (!(c in node.children)) {
node.children[c] = new TrieNode();
}
node = node.children[c];
}
node.isEnd = true;
}
search(word) {
let node = this.root;
for (const c of word) {
if (!(c in node.children)) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
startsWith(prefix) {
let node = this.root;
for (const c of prefix) {
if (!(c in node.children)) {
return false;
}
node = node.children[c];
}
return true;
}
}
The JavaScript details worth a closer look:
- An object as a map.
{}with letters as keys works as a dictionary here. Reading a missing key givesundefined, so the code checks for the key first and never reads a child that isn't there. intests for a key."a" in node.childrenis true when the key exists, even if its value wereundefined. The!( )around it negates the whole test. Writing!c in node.childrenwould negatecfirst and give the wrong test.- Inherited names.
inalso sees properties an object inherits, so"constructor" in {}istrue. That can't affect this code: the keys tested are single lowercase letters, and no inherited property has a one-letter name. AMapwould avoid the question altogether. for...ofover a string gives one character at a time, as a one-character string.- Shared walking code.
searchandstartsWithrepeat the same loop. That is fine for this lesson, and a helper that returns the final node (ornull) would remove the repetition. nodeis a moving reference. Reassigningnodeonly moves the pointer. The nodes stay in the trie, linked from their parents'children.
Complexity
Time: O(L) per operation. Each operation does one step per letter of its argument, and every step is a key test and a lookup in an object, plus at most one node creation. The number of words stored doesn't matter.
Space: O(N) in total, where N is the number of letters in the inserted words, in the worst case where no two words share a prefix. Shared prefixes are stored once. search and startsWith use O(1) extra space, and insert adds at most L nodes.
Edge cases and common mistakes
- A word that is a prefix of another. After inserting
"car"and"cart",search("car")andsearch("cart")are both true, becauseisEndis set on two different nodes. - A prefix that isn't a word. With
"car"and"cart"inserted,startsWith("ca")is true andsearch("ca")is false. - Nothing longer inserted. After inserting
"dog",startsWith("dogs")andsearch("dogs")are false, andsearch("do")is false. - Inserting a word twice. The second walk finds every node already there and sets
isEndtotrueagain. Nothing changes. - Returning
truefromsearchwithout checkingisEnd. That turnssearchintostartsWith. - Forgetting to set
isEndininsert. Then no word is ever found bysearch. - Creating nodes while searching.
searchandstartsWithmust only read. If they created missing children, later calls would answer wrongly for prefixes nobody inserted. - An empty string. The tests only use words and prefixes of at least one letter. If you try it yourself,
startsWith("")returnstrueandsearch("")returnsfalseunless the root'sisEndis set.
Testing
Results of the search and startsWith calls, in order:
insert("apple"),search("apple"),search("app"),startsWith("app"),insert("app"),search("app")givestrue false true true.insert("car"),insert("cart"),startsWith("ca"),search("ca"),startsWith("cat"),search("cart")givestrue false false true.insert("dog")twice, thensearch("dog"),startsWith("dog"),search("do"),startsWith("dogs"),search("dogs")givestrue true false false false.
