Problem description:

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.

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class TrieNode:
def __init__(self):
self.child = defaultdict(TrieNode)
self.count = 0
self.tail = 0

class Trie:
def __init__(self):
self.root = TrieNode()

def insert(self, word: str) -> None:
p = self.root
for c in word:
p = p.child[c]
p.count += 1
p.tail += 1

def countWordsEqualTo(self, word: str) -> int:
p = self.root
for c in word:
if c in p.child:
p = p.child[c]
else:
return 0
return p.tail

def countWordsStartingWith(self, prefix: str) -> int:
p = self.root
for c in prefix:
if c in p.child:
p = p.child[c]
else:
return 0
return p.count

def erase(self, word: str) -> None:
p = self.root
for c in word:
if c in p.child:
p = p.child[c]
p.count -= 1
p.tail -= 1


# 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)

time complexity: $O()$
space complexity: $O()$
reference:
related problem: