Implement Trie II (Prefix Tree) - Problem

A Trie (pronounced as "try") or prefix tree is a tree data structure that efficiently stores and retrieves keys in a dataset of strings. Think of it as a digital dictionary that can instantly tell you not just if a word exists, but also how many times it appears and how many words start with a given prefix!

This enhanced version of the classic Trie supports:

  • insert(word) - Add a word to the trie (can be added multiple times)
  • countWordsEqualTo(word) - Count how many instances of this exact word exist
  • countWordsStartingWith(prefix) - Count how many words start with this prefix
  • erase(word) - Remove one instance of this word from the trie

Real-world applications: Autocomplete systems (like Google Search), spell checkers, word frequency analyzers, and search engines all rely on similar data structures!

Input & Output

example_1.py โ€” Basic Operations
$ Input: trie = Trie() trie.insert("apple") trie.insert("apple") trie.countWordsEqualTo("apple") // return 2 trie.countWordsStartingWith("app") // return 2 trie.erase("apple") trie.countWordsEqualTo("apple") // return 1
โ€บ Output: 2, 2, 1
๐Ÿ’ก Note: We insert "apple" twice, so countWordsEqualTo returns 2. Both instances start with "app", so countWordsStartingWith returns 2. After erasing once, only 1 instance remains.
example_2.py โ€” Prefix Counting
$ Input: trie = Trie() trie.insert("car") trie.insert("card") trie.insert("care") trie.insert("cat") trie.countWordsStartingWith("car") // return 3 trie.countWordsStartingWith("ca") // return 4
โ€บ Output: 3, 4
๐Ÿ’ก Note: Three words start with "car" (car, card, care), and four words start with "ca" (all of them including cat).
example_3.py โ€” Edge Cases
$ Input: trie = Trie() trie.countWordsEqualTo("missing") // return 0 trie.countWordsStartingWith("x") // return 0 trie.erase("nonexistent") // no effect trie.insert("a") trie.erase("a") trie.countWordsEqualTo("a") // return 0
โ€บ Output: 0, 0, 0
๐Ÿ’ก Note: Querying non-existent words returns 0. Erasing non-existent words has no effect. After inserting and erasing "a", the count becomes 0.

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, countWordsEqualTo, countWordsStartingWith, and erase
  • It is guaranteed that for any function call to erase, the word will exist in the trie

Visualization

Tap to expand
Trie Operations: Building and QueryingStep 1: Empty TrierootW:0 P:0Step 2: Insert "car"rootcP:1aP:1rW:1 P:1Step 3: Insert "card"rootcP:2aP:2rW:1 P:2dW:1Step 4: Query "car*"rootcP:2aP:2rP:2 โ†dW:1Answer: 2Legend:โ€ข W:n = Word count (words ending at this node)โ€ข P:n = Prefix count (words passing through this node)โ€ข Blue highlight = Query target nodeTime Complexity: O(m) where m = word lengthSpace Complexity: O(ALPHABET_SIZE ร— N ร— M)Much faster than O(nร—m) brute force approach!
Understanding the Visualization
1
Initialize Empty Trie
Start with root node containing empty counters
2
Insert 'car'
Create path cโ†’aโ†’r, increment prefix counts along path, set word count at end
3
Insert 'card'
Reuse existing cโ†’aโ†’r path, extend with 'd', update all counters
4
Query prefix 'car'
Navigate to 'r' node and return its prefix count
Key Takeaway
๐ŸŽฏ Key Insight: By storing word count and prefix count at each node, the Trie enables O(m) operations instead of O(nร—m) linear search, making it highly efficient for prefix-based queries.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
42.0K Views
High Frequency
~25 min Avg. Time
1.9K 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