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 string word into the trie.
  • int countWordsEqualTo(String word) Returns the number of instances of the string word in the trie.
  • int countWordsStartingWith(String prefix) Returns the number of strings in the trie that have the string prefix as a prefix.
  • void erase(String word) Erases the string word from 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
Trie II (Prefix Tree) Implementation INPUT Operations: 1. Trie() 2. insert("apple") 3. insert("app") 4. countWordsEqualTo("app") 5. countWordsStartingWith("app") 6. erase("app") Trie Structure: root a p p l e end:1 end:1 ALGORITHM STEPS 1 Node Structure children[26], prefixCount, endCount for each node 2 Insert Operation Traverse/create nodes, increment prefixCount++ endCount++ at word end 3 Count Operations EqualTo: return endCount StartsWith: return prefixCount 4 Erase Operation Traverse path, decrement prefixCount--, endCount-- Execution Trace: insert("apple") --> OK insert("app") --> OK countEqualTo("app") --> 1 countStartsWith("app") --> 2 erase("app"), countEqualTo --> 0 FINAL RESULT Output Array: [null, null, null, 1, 2, null, 0] Step-by-step Results: Trie() --> null (init) insert("apple") --> null insert("app") --> null countEqualTo("app") --> 1 countStartsWith("app") --> 2 erase("app") --> null countEqualTo("app") --> 0 ("app" was erased!) Final Trie State: Only "apple" remains Key Insight: Each node stores two counters: prefixCount (words passing through) and endCount (words ending here). This enables O(n) operations for all methods where n = word length. Erase decrements counters along the path. TutorialsPoint - Implement Trie II (Prefix Tree) | Optimized Trie Implementation
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
23.5K Views
High Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen