- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/implement-trie-prefix-tree
- topics: Trie
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.boolean search(String word)Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
class Trie:
def __init__(self):
self.trie = {}
def insert(self, word: str) -> None:
pointer = self.trie
i = 0
while i < len(word):
if not word[i] in pointer:
while i < len(word):
pointer[word[i]] = {}
pointer = pointer[word[i]]
i += 1
else:
pointer = pointer[word[i]]
i += 1
if not "$" in pointer:
pointer["$"] = True
def search(self, word: str) -> bool:
pointer = self.trie
for c in word:
if c in pointer:
pointer = pointer[c]
else:
return False
return "$" in pointer
def startsWith(self, prefix: str) -> bool:
pointer = self.trie
for c in prefix:
if c in pointer:
pointer = pointer[c]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)