Implement Trie (Prefix Tree)
mediumNeetCode 150designtriestrings
Problem
Design a prefix tree supporting inserting a word, checking whether a full word exists, and checking whether any stored word starts with a given prefix.
Examples
Input: insert "apple"; search "apple"; search "app"; startsWith "app"
Output: true, false, true
"app" is a prefix but not an inserted word.
Constraints
- • 1 <= word and prefix length <= 2000
- • Lowercase English letters
- • At most 3 * 10^4 calls
Hints(tap to reveal)
- 1. Each node holds child links per letter and an end marker.
- 2. Walk letter by letter from the root.
Optimal approach(spoiler)
- Represent each node with a map of child letters and an end-of-word flag.
- Insert by walking or creating child nodes for each character, marking the final node.
- Search by walking the path and checking the end flag.
- Prefix check walks the path without requiring the end flag.
- Operations are O(length of the key).
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor