LeetCode 208. Implement Trie (Prefix Tree)
🧩 Problem Description
A trie (pronounced try) or prefix tree is a tree data structure used to efficiently store and search strings in a dataset of strings.
Implement the Trie
class:
Trie()
initializes the object.void insert(String word)
inserts the stringword
into the trie.boolean search(String word)
returnstrue
if the stringword
is in the trie (i.e., was inserted before), andfalse
otherwise.boolean startsWith(String prefix)
returnstrue
if there is a previously inserted stringword
that starts with the given prefix.
💬 Example
1 | Input: |
💡 Approach: Trie Node Structure
We build a tree where each node contains up to 26 children (for each lowercase letter).
Each node also keeps a boolean flag isEnd
to mark the end of a word.
🔢 Java Code
1 | class Trie { |
⏱ Complexity Analysis
- Insert: O(L), where L = length of the word
- Search: O(L)
- StartsWith: O(P), where P = length of the prefix
- Space: O(N * L), where N = number of words, L = average word length
✍️ Summary
- Trie is a powerful data structure for string searching.
- Operations are efficient: O(L).
- Widely used in autocomplete, spell check, IP routing, and word games.
Related problems:
lc-211
— Design Add and Search Words Data Structurelc-212
— Word Search IIlc-648
— Replace Wordslc-720
— Longest Word in Dictionary