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 spell checker.
Implement a Trie with the following methods:
Trie()
: Initializes the trie object.void insert(String word)
: Inserts the string word
into the trie.boolean search(String word)
: Returns true if the string word
is in the trie (i.e., was inserted before), and false otherwise.boolean startsWith(String prefix)
: Returns true if there is a previously inserted string that has the prefix prefix
, and false otherwise.children
where each key is a character and the value is another Trie node.is_word
to mark the end of a word.is_word
flag.class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_word
def startsWith(self, prefix: str) -> bool:
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
Here, creating/traversing nodes takes linear time with respect to the length of the word or prefix being processed.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?