Skip to content

Instantly share code, notes, and snippets.

@siavashk
Created December 2, 2024 23:30
Show Gist options
  • Save siavashk/1c292b1891a2933346abb7e1949ca380 to your computer and use it in GitHub Desktop.
Save siavashk/1c292b1891a2933346abb7e1949ca380 to your computer and use it in GitHub Desktop.
Trie
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
"""
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word):
"""
Searches for a word in the trie.
Returns True if the word exists, False otherwise.
"""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end_of_word
def starts_with(self, prefix):
"""
Returns True if there is any word in the trie
that starts with the given prefix.
"""
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
def delete(self, word):
"""
Deletes a word from the trie if it exists.
"""
def _delete(node, word, depth):
if not node:
return False
# If the last character of the word is being processed
if depth == len(word):
if not node.is_end_of_word:
return False # Word not found
node.is_end_of_word = False
# If the node has no children, delete it
return len(node.children) == 0
char = word[depth]
if char in node.children:
should_delete_child = _delete(node.children[char], word, depth + 1)
if should_delete_child:
del node.children[char]
# Return True if the current node is also not the end of a word
# and has no other children
return not node.is_end_of_word and len(node.children) == 0
return False
_delete(self.root, word, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment