Implement Trie (Prefix Tree)
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Implement Trie (Prefix Tree)
Implement a trie which supports
insert, search, and startsWith operations.Examples
Input: ["Trie", "insert", "search", "search", "startsWith"]
[[], ["apple"], ["apple"], ["app"], ["app"]]
Output: [null, null, true, false, true]
Approach 1
Level I: HashMap-based Trie
Intuition
Flexible implementation using a HashMap for children, suitable for any character set (Unicode).
⏱ O(L)💾 O(N * L)
Detailed Dry Run
Insert 'apple': R -> a -> p -> p -> l -> e (end).
Approach 2
Level III: Array-based Trie (Optimal)
Intuition
Static array
[26] for lowercase English. Fastest possible access with minimal memory overhead for dense tries.⏱ O(L)💾 O(N * L * 26)
Detailed Dry Run
Insert 'cat': root.children['c'-'a'] -> node1.children['a'-'a'] -> node2.children['t'-'a'] -> node3(isEnd=true).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.