#208
Implement Trie (Prefix Tree)
medium· Triesruns: 0A trie is a tree data structure used to efficiently store and retrieve keys in a set of strings. Implement the Trie class with insert(word), search(word) returning true if the exact word is in the trie, and startsWith(prefix) returning true if any inserted word has the given prefix.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 846
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
curr = self.root
for c in word:
if c not in curr.children:
curr.children[c] = TrieNode()
curr = curr.children[c]
curr.is_end = True
def search(self, word: str) -> bool:
node = self._find(word)
return node is not None and node.is_end
def startsWith(self, prefix: str) -> bool:
return self._find(prefix) is not None
def _find(self, prefix: str) -> "TrieNode | None":
curr = self.root
for c in prefix:
if c not in curr.children:
return None
curr = curr.children[c]
return curr
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.