Implement Trie II (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.int countWordsEqualTo(String word)Returns the number of instances of the stringwordin the trie.int countWordsStartingWith(String prefix)Returns the number of strings in the trie that have the stringprefixas a prefix.void erase(String word)Erases the stringwordfrom the trie.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo"]
arguments = [[], ["apple"], ["app"], ["app"], ["app"], ["app"], ["app"]]
›
Output:
[null, null, null, 1, 2, null, 0]
💡 Note:
Initialize trie, insert "apple" and "app". Count "app": 1 word exactly matches. Count with prefix "app": 2 words ("app" and "apple"). After erasing "app", count becomes 0.
Example 2 — Multiple Insertions
$
Input:
operations = ["Trie", "insert", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith"]
arguments = [[], ["app"], ["app"], ["apple"], ["app"], ["app"]]
›
Output:
[null, null, null, null, 2, 3]
💡 Note:
After inserting "app" twice and "apple" once: exactly 2 instances of "app", and 3 total words starting with "app" prefix.
Example 3 — Empty Prefix Search
$
Input:
operations = ["Trie", "insert", "countWordsStartingWith", "countWordsEqualTo"]
arguments = [[], ["hello"], [""], [""]]
›
Output:
[null, null, 1, 0]
💡 Note:
Empty prefix matches all words (1 word total). Empty string as exact word match returns 0 since we didn't insert empty string.
Constraints
- 1 ≤ word.length, prefix.length ≤ 2000
- word and prefix consist only of lowercase English letters
- At most 3 × 104 calls will be made to insert, countWordsEqualTo, countWordsStartingWith, and erase
- It is guaranteed that for any function call to erase, the string word will exist in the trie
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sequence of operations: insert, count, erase
2
Process
Build tree structure with character nodes
3
Output
Return counts based on tree traversal
Key Takeaway
🎯 Key Insight: Store strings as tree paths where each node tracks word endings and prefix counts for O(m) operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code