Implement Trie II (Prefix Tree) Problem
#1804
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1804.
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.
Example 1:
Input
["Trie", "insert", "insert", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsEqualTo", "countWordsStartingWith", "erase", "countWordsStartingWith"]
[[], ["apple"], ["apple"], ["apple"], ["app"], ["apple"], ["apple"], ["app"], ["apple"], ["app"]]
Output
[null, null, null, 2, 2, null, 1, 1, null, 0]
Explanation
Trie trie = new Trie();
trie.insert("apple"); // Inserts "apple".
trie.insert("apple"); // Inserts another "apple".
trie.countWordsEqualTo("apple"); // There are two instances of "apple" so return 2.
trie.countWordsStartingWith("app"); // "app" is a prefix of "apple" so return 2.
trie.erase("apple"); // Erases one "apple".
trie.countWordsEqualTo("apple"); // Now there is only one instance of "apple" so return 1.
trie.countWordsStartingWith("app"); // return 1
trie.erase("apple"); // Erases "apple". Now the trie is empty.
trie.countWordsStartingWith("app"); // return 0
Constraints:
1 <= word.length, prefix.length <= 2000wordandprefixconsist only of lowercase English letters.- At most
3 * 10^4calls in total will be made toinsert,countWordsEqualTo,countWordsStartingWith, anderase. - It is guaranteed that for any function call to
erase, the stringwordwill exist in the trie.
Solution
Approach: Trie with Counters
Each trie node has 26 child pointers and two counters: v, the number of inserted words that end at this node, and pv, the number of inserted words that pass through it.
insert: walk down the word, creating missing nodes and increasingpvof each node on the path, then increasevof the last node.countWordsEqualTo: find the node for the word and return itsv, or 0 if the path does not exist.countWordsStartingWith: find the node for the prefix and return itspv, or 0.erase: walk down the word decreasingpvalong the path, then decreasevof the last node.
Complexity: each operation takes O(L), where L is the length of the word.
class Trie:
def __init__(self):
self.children = [None] * 26
self.v = self.pv = 0
def insert(self, word: str) -> None:
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.pv += 1
node.v += 1
def countWordsEqualTo(self, word: str) -> int:
node = self.search(word)
return 0 if node is None else node.v
def countWordsStartingWith(self, prefix: str) -> int:
node = self.search(prefix)
return 0 if node is None else node.pv
def erase(self, word: str) -> None:
node = self
for c in word:
idx = ord(c) - ord('a')
node = node.children[idx]
node.pv -= 1
node.v -= 1
def search(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return None
node = node.children[idx]
return node
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.countWordsEqualTo(word)
# param_3 = obj.countWordsStartingWith(prefix)
# obj.erase(word)