Implement Trie (Prefix Tree) - Problem
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()Initializes the trie object.void insert(String word)Inserts the stringwordinto the trie.boolean search(String word)Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
Input & Output
Example 1 — Basic Trie Operations
$
Input:
operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], values = ["", "apple", "apple", "app", "app", "app", "app"]
›
Output:
[null, null, true, false, true, null, true]
💡 Note:
Create trie, insert "apple", search "apple" (found), search "app" (not found), check prefix "app" (exists), insert "app", search "app" (now found)
Example 2 — Multiple Words with Shared Prefix
$
Input:
operations = ["Trie", "insert", "insert", "search", "startsWith"], values = ["", "car", "card", "care", "car"]
›
Output:
[null, null, null, false, true]
💡 Note:
Insert "car" and "card", search "care" (not found), but "car" is a valid prefix
Example 3 — Single Character Operations
$
Input:
operations = ["Trie", "insert", "search", "startsWith"], values = ["", "a", "a", "a"]
›
Output:
[null, null, true, true]
💡 Note:
Edge case with single character: insert "a", search "a" (found), "a" starts with "a"
Constraints
- 1 ≤ word.length, prefix.length ≤ 2000
- word and prefix consist only of lowercase English letters
- At most 3 × 104 calls in total will be made to insert, search, and startsWith
Visualization
Tap to expand
Understanding the Visualization
1
Input
Series of operations: insert, search, startsWith with word values
2
Process
Build tree structure sharing common prefixes between words
3
Output
Array of results: null for insert, boolean for search/startsWith
Key Takeaway
🎯 Key Insight: A trie shares common prefixes in a tree structure, making prefix operations extremely efficient
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code