Skip to content

Instantly share code, notes, and snippets.

@Jay-davisphem
Last active July 14, 2024 15:02
Show Gist options
  • Select an option

  • Save Jay-davisphem/990e5f84150b3ccf01ecab88768e42df to your computer and use it in GitHub Desktop.

Select an option

Save Jay-davisphem/990e5f84150b3ccf01ecab88768e42df to your computer and use it in GitHub Desktop.
Trie, TrieNode implementation
class TrieNode:
N = 62
def __init__(self):
self.is_word = False
self.word = ''
self.children = [None]*TrieNode.N
def __str__(self):
return f"TrieNode<'{self.word}'>"
def __repr__(self):
return self.__str__()
class Trie:
a = 97
A = 65
def __init__(self):
self.root = TrieNode()
def index(self, c: str):
i = 0
if 'A' <= c <= 'Z':
i = ord(c) - self.A
elif 'a' <= c <= 'z':
i = ord(c) - self.a + 26
elif '0' <= c <= '9':
i = ord(c) - ord('0') + 26 + 26
else:
raise f'Invalid character "{c}"'
return i
def insert(self, word: str):
cur = self.root
for c in word:
if cur.children[self.index(c)] == None:
cur.children[self.index(c)] = TrieNode()
cur.children[self.index(c)].word = cur.word + c
cur = cur.children[self.index(c)]
cur.is_word = True
def _search(self, word: str):
cur = self.root
for c in word:
if cur.children[self.index(c)] == None:
return False
cur = cur.children[self.index(c)]
return cur
def search(self, word: str):
res = self._search(word)
if res == False:
return res
return res.is_word
def startsWith(self, word: str):
res = self._search(word)
if res == False:
return res
return True
# Space Complexity: O(W * N) - W is the average word length, N is the number of words in the Trie (Just on creation)
# Time Complexity:
# - insert: O(W) - W is the length of the word being inserted
# - search/startsWith: O(P) - P is the length of the word being searched/having the prefix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment