Insert words, search them and check prefixes. A tree of letters lets words that share a prefix share a path.
▼The problem
LeetCode 208, Implement Trie (Prefix Tree) (Medium). Build a structure with insert(word), search(word) (is this exact word stored?) and startsWith(prefix) (does any stored word begin with it?).
Example: insert car, cart, cat, dog. Then search("car") → True, search("ca") → False (only a prefix), startsWith("ca") → True, search("cart") → True, search("cow") → False (no o under c: walk returns None).
class TrieNode:
def __init__(self):
self.children = {} # letter -> node
self.is_end = False # a word ends here
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 walk(self, s):
node = self.root
for ch in s:
if ch not in node.children:
return None # dead end
node = node.children[ch]
return node
def search(self, word):
node = self.walk(word)
return node is not None and node.is_end
def startsWith(self, prefix):
return self.walk(prefix) is not NoneTRY IT ON LEETCODE ▶The solution
class TrieNode:
def __init__(self):
self.children = {} # letter -> node
self.is_end = False # a word ends here
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 walk(self, s):
node = self.root
for ch in s:
if ch not in node.children:
return None # dead end
node = node.children[ch]
return node
def search(self, word):
node = self.walk(word)
return node is not None and node.is_end
def startsWith(self, prefix):
return self.walk(prefix) is not NoneTranscript
Implement Trie. Build a structure with three operations. Insert adds a word. Search asks whether that exact word was stored. And starts with asks whether any stored word begins with a given prefix.
Insert car, cart, cat and dog. Search car: true. Search C A: false, it's only a prefix. But starts with C A is true: car, cart and cat all begin that way.
The simple way keeps a list and compares the query with every word. With a hundred thousand words, every lookup scans all of them, even when the answer is no.
A trie is a tree of letters. Each edge is one letter, so a path from the root spells a word. Words with the same prefix share a path: car, cart and cat all walk through C, then A. Each node keeps a map of its children, and an end flag, drawn as a gold flower, where a whole word stops.
In code, insert starts at the root and walks one letter at a time. If that letter's child is missing, it adds a new node. At the end, it flags the last node. Search and starts with share one walk. A missing letter is a dead end: false. If the walk gets through, search also needs the flag. Starts with doesn't.
Let's grow it. Car adds three nodes and a flower on R. Cart reuses C A R and adds T. Cat shares C A, then branches. Dog starts a new branch at the root. Search C A: the path exists, but A has no flower: false. Starts with C A: true. Search cart: four steps, ending on a flower: true. Search cow: there's no O under C. Dead end.
Each operation takes one step per letter, so the time depends on the word's length, not on how many words are stored. Space grows with the letters inserted: thirteen letters made only eight nodes, because shared prefixes are stored once.
Shared prefixes, one step per letter. That's Implement Trie.