MEDIUM NC#61 Blind #71 Tries - Prefix Tree
208. Implement Trie (Prefix Tree)
๐ Problem
Implement a Trie with insert, search, and startsWith methods. - insert(word): Inserts word into trie - search(word): Returns true if word is in trie - startsWith(prefix): Returns true if any word with this prefix exists
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Trie nodes have children Map and isEndOfWord flag
- โ insert: traverse/create nodes for each character, mark last as end
- โ search: traverse nodes, return isEndOfWord at the end
- โ startsWith: traverse nodes, return true if all characters found
- โ Time: O(L) per operation where L = word/prefix length
- โ Space: O(total characters inserted)
๐ ๏ธ Hints & Pitfalls
Hints
- โขTrie nodes have children Map and isEndOfWord flag
- โขinsert: traverse/create nodes for each character, mark last as end
- โขsearch: traverse nodes, return isEndOfWord at the end
Common Pitfalls
- โขstartsWith: traverse nodes, return true if all characters found
- โขTime: O(L) per operation where L = word/prefix length
- โขSpace: O(total characters inserted)
๐งช Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
(() => { const trie = new Trie(); return trie.insert('apple'); })(); Expected:
null Test Case 2
Not run Input:
(() => { const trie = new Trie(); trie.insert('apple'); return trie.search('apple'); })(); Expected:
true Test Case 3
Not run Input:
(() => { const trie = new Trie(); trie.insert('apple'); trie.search('apple'); return trie.search('app'); })(); Expected:
false ๐ Code Editor
๐ค Output