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.
The class Trie has three methods:
insert(word)adds a word;search(word)returnstrueonly if that exact word was inserted;startsWith(prefix)returnstrueif some inserted word begins withprefix. A word counts as a prefix of itself.
After insert("apple"), search("apple") is true, but search("app") is false, because "app" was never inserted as a word, while startsWith("app") is true. After insert("app"), search("app") becomes true.
Approach
Scanning a list of all inserted words for every question costs time that grows with the number of words. A trie makes each operation depend only on the length L of the word or prefix: follow its letters from the root, one level per letter.
Two pieces of data make that work:
- each
TrieNodekeepschildren, an object that maps a letter to the child node for that letter, so the next step is found directly and only letters that some word uses take space; - each node also keeps a flag,
isEnd, that istruewhere an inserted word ends. After inserting"apple"the nodes for"app"and"apple"both exist, and only the flag says which of them ends a word. That flag is the whole difference betweensearchandstartsWith.
The root stands for the empty prefix, so an empty trie is a root with no children.
Step by step
- The node's children. In
TrieNode,childrenhas the typeRecord<string, TrieNode>, an object whose keys are strings and whose values areTrieNodes, and starts as the empty object{}. - The end flag.
isEndis abooleanthat starts asfalse. - The root. In
Trie,rootis a newTrieNode. insert: start at the root. A variablenodebegins atthis.rootand walks down as the letters are read.- Loop over the letters. A
for...ofloop gives each charactercofword. - Create the path when it is missing. If
cis not a key ofnode.children, store a newTrieNodeunder it. The test is!(c in node.children). - Move down.
nodebecomesnode.children[c]. The child exists now, whether it was there before or was just created. - Mark the end. After the loop,
nodeis the node of the whole word, andnode.isEndbecomestrue. search: the same walk, creating nothing. If a letter has no child, returnfalse: no inserted word goes this way.- Return the flag. After the loop, return
node.isEnd. Reaching the node is not enough, because the path for"app"exists after inserting"apple"although no word ends there. startsWith: the same walk again. A missing letter givesfalse.- Return
true. If every letter of the prefix had a child, its path exists, and every node of the trie lies on the path of some inserted word, so some word starts with it.
The solution in TypeScript
class TrieNode {
children: Record<string, TrieNode> = {};
isEnd: boolean = false;
}
class Trie {
root: TrieNode = new TrieNode();
insert(word: string): void {
let node: TrieNode = 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: string): boolean {
let node: TrieNode = this.root;
for (const c of word) {
if (!(c in node.children)) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
startsWith(prefix: string): boolean {
let node: TrieNode = this.root;
for (const c of prefix) {
if (!(c in node.children)) {
return false;
}
node = node.children[c];
}
return true;
}
}
Details for TypeScript:
Record<string, TrieNode>is only a type. When the code is compiled to JavaScript,childrenis just a plain object created by{}, and the type is erased.- The
inoperator tests whether a key exists in an object, soc in node.childrenistruewhen some inserted word continues withcat this node. It also sees properties an object inherits:"toString" in {}istrue. For the single lowercase letters of this lesson no key like that exists, so the test is exact. If the keys could be longer words, aMap<string, TrieNode>would avoid the surprise. - Field initializers such as
root: TrieNode = new TrieNode();run for each new instance, so eachTriegets its own root and eachTrieNodeits ownchildrenobject. for (const c of word)iterates over the characters of a string, each one a one-character string, which suits the keys ofchildren.
Complexity
Time: O(L) for each operation, where L is the length of the word or prefix: one loop turn per letter, and looking up a key in an object, creating a node and moving down are each constant work. Space: a trie holds at most one node per letter of each inserted word, so O(total letters) in the worst case; words with a shared beginning share nodes, which saves space.
Edge cases and common mistakes
- A word that is a prefix of another. After
insert("car")andinsert("cart"),search("car")istrueandstartsWith("ca")istrue, butsearch("ca")isfalse. - Inserting the same word twice. The second
insert("dog")finds the whole path and setsisEndtotrueagain: nothing changes. - A prefix of itself. After
insert("dog"),startsWith("dog")istrue, whilestartsWith("dogs")andsearch("do")arefalse. - Returning
truefromsearchat the end of the walk. It would make every prefix of an inserted word look like a word. The answer must benode.isEnd. - Creating nodes in
searchorstartsWith. Those methods only read. Creating children there would make laterstartsWithcalls succeed for prefixes of words that were never inserted. - Forgetting to mark the end. Without
node.isEnd = trueafter the loop ininsert,searchcould never returntrue.
Testing
| Calls | Results of search and startsWith |
|---|---|
| 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" twice, search "dog", startsWith "dog", search "do", startsWith "dogs", search "dogs" | true, true, false, false, false |
