Implement a trie with insert(word), search(word) (is the whole word stored?) and startsWith(prefix) (is any stored word prefixed by it?). Input is a LeetCode-style list of operations.
For lowercase words, store children in an array indexed by letter. Lookups are direct, but every node reserves 26 slots.
1class TrieNode { kids: (TrieNode | undefined)[] = new Array(26); end = false; }2const idx = (c: string) => c.charCodeAt(0) - 97;3class Trie {4root = new TrieNode();5insert(word: string): void {6let n = this.root;7for (const c of word) n = n.kids[idx(c)] ??= new TrieNode();8n.end = true;9}10private walk(s: string): TrieNode | null {11let n = this.root;12for (const c of s) { const k = n.kids[idx(c)]; if (!k) return null; n = k; }13return n;14}15search(word: string): boolean { return this.walk(word)?.end ?? false; }16startsWith(prefix: string): boolean { return this.walk(prefix) !== null; }17}
Create an empty trie.
Space: play/pause · ←/→: step