Trie (Prefix Tree)
Use when: prefix matching, autocomplete, word search with wildcards, longest common prefix.
Signal words: prefix, starts with, dictionary, word search, autocomplete.
Implementation
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def search(self, word):
node = self.root
for ch in word:
if ch not in node.children:
return False
node = node.children[ch]
return node.is_end
def starts_with(self, prefix):
node = self.root
for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return TrueKey Insight
Each path from root to a node represents a prefix. Each path to an is_end node represents a complete word.