Implement Trie (Prefix Tree)
Problem (restated)
Implement Trie with insert, search (full word), and startsWith (prefix).
Intuition
Children map/array per node; end-of-word flag.
Approaches
Trie insert/search/startsWith
UnverifiedIdea. walk edges per char; create on insert; search needs end flag.
Walkthrough. insert apple; search apple true; search app false; startsWith app true.
Trade-offs. Array[26] fastest for lowercase; map generalizes.
class TrieNode {
children: Map<string, TrieNode> = new Map();
end = false;
}
export class Trie {
private root = new TrieNode();
insert(word: string): void {
let n = this.root;
for (const c of word) {
if (!n.children.has(c)) n.children.set(c, new TrieNode());
n = n.children.get(c)!;
}
n.end = true;
}
search(word: string): boolean {
const n = this.walk(word);
return !!n && n.end;
}
startsWith(prefix: string): boolean {
return !!this.walk(prefix);
}
private walk(s: string): TrieNode | null {
let n = this.root;
for (const c of s) {
if (!n.children.has(c)) return null;
n = n.children.get(c)!;
}
return n;
}
}
class TrieNode {
children: Map<string, TrieNode> = new Map();
end = false;
}
export class Trie {
private root = new TrieNode();
insert(word: string): void {
let n = this.root;
for (const c of word) {
if (!n.children.has(c)) n.children.set(c, new TrieNode());
n = n.children.get(c)!;
}
n.end = true;
}
search(word: string): boolean {
const n = this.walk(word);
return !!n && n.end;
}
startsWith(prefix: string): boolean {
return !!this.walk(prefix);
}
private walk(s: string): TrieNode | null {
let n = this.root;
for (const c of s) {
if (!n.children.has(c)) return null;
n = n.children.get(c)!;
}
return n;
}
}
Template connection
A map of children per node. insert creates the missing edge for each character and marks the last node. search requires that mark. startsWith returns once the walk stays on the trie.
Reflection
searchneeds the end-of-word flag.startsWithonly needs the walk not to break.- A missing letter is absent. The empty word is the root’s flag. Inserting the same word twice still counts once.
- One child per letter. A length-26 array fits a dense alphabet. A map fits a sparse one.