Learn DSA
Depth-First Search
Greedy Algorithms
Trie
Implement Trie Methods
medium
DESCRIPTION
Implement the search and delete methods of a Trie.
- search(word) returns true if the word is in the Trie, and false otherwise.
- delete(word) removes the word from the Trie, and does not return a value.
The creation of the Trie and the insert method are already implemented for you.
The test cases include two parameters:
- initialWords: a list of words to add to the Trie,
- commands: a list of commands to run. Each command is a tuple, where the first element is either "search" or "delete", and the second element is the word to search or delete.
The test cases will create the Trie with the initial words, and then run the commands in order, and compare the output to the expected output. Note we only compare the output of the search commands, not the delete commands.
Input:
Output: [True, True, False, False]
Explanation:
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
Implement the search and delete method in the Trie class.
Run your code to see results here
Have suggestions or found something wrong?
Explanation
Search
def search(self, word):"""Search the trie for the given word.Returns True if the word exists in the trie, False otherwise"""# start from the root nodenode = self.root# traverse down the triefor char in word:if char not in node.children:# the word does not exist in the triereturn Falsenode = node.children[char]return node.is_end_of_word
Delete
- They are not the end of any word
- They don't have any children
- The current node is not the end of any word (not node.isEndOfWord) AND
- The current node has no children (len(node.children) == 0)
- If the boolean is True, it deletes the child node from its dictionary of children. The parent node then returns if it should be deleted as well.
- If the boolean is False, it does not delete the child node and returns False, which prevents any further deletions.
def delete(self, word):"""Deletes the given the word from the Trie.Returns None."""def _delete(node, index):# base case: We have reached the end of the wordif index == len(word):if not node.isEndOfWord:return Falsenode.isEndOfWord = Falsereturn len(node.children) == 0char = word[index]if char not in node.children:return Falsedelete_child = _delete(node.children[char], index + 1)if delete_child:del node.children[char]return not node.isEndOfWord and len(node.children) == 0return Falseif _delete(self.root, 0):if word and word[0] in self.root.children:# delete first character from the root's childrendel self.root.children[word[0]]
Login to track your progress
Your account is free and you can post anonymously if you choose.