A tree of letters: how autocomplete works
🌍 In real life. Type "ca" on a phone and it offers car, cat, cake. It doesn't read through its whole dictionary to find them. It follows the letters c, then a, to one spot, and everything stored below that spot starts with "ca". A printed dictionary does the same with its thumb index: open at C, then look for the a's.
The structure behind it is a trie (said like "try", from retrieval): a tree whose branches are letters. Words that start the same way share the same first branches, so a trie is the natural home for prefix questions: "which words start with…?", "is this the start of any word?".
The idea in one sentence: a trie stores words one letter per node: the root is empty, each node's children are the letters that can come next, and a flag marks the nodes where a word ends.
Its words:
- trie: a tree of letters for storing words
- root: the empty start node; every word begins from it
- children: a node's next letters, here a dict from letter to node
- end flag (
is_end): True at a node where a word finishes; needed because "car" ends inside "cart" - prefix: the start of a word; every node is the end of exactly one prefix, the letters on the path from the root
How inserting works, step by step:
- start at the root
- for each letter: if the current node has no child for it, make one; then step down into that child
- after the last letter, set the node's end flag
Watch car, cart, care, cat and dog go in: cart only adds a t, because c, a, r are already there:
Why it is correct. Every word becomes exactly one path from the root, one node per letter, and two words share a node exactly when they share the prefix that ends there. So following a word's letters always leads to the same node, and the end flag on it records whether that exact word was inserted, not just some longer word that passes through.
What it costs, by counting. Inserting a word of L letters takes L steps, whatever else is in the trie: O(L). The trie never has more nodes than the total number of letters inserted, and shared prefixes make it fewer. The five words above have 17 letters but need only 9 nodes, because car, cart, care and cat share c and a, and three of them share r too.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # does a word end here?
def insert(root, word):
node = root
for ch in word:
if ch not in node.children: # only make a node when the letter is missing
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def count_nodes(node):
return sum(1 + count_nodes(child) for child in node.children.values())
root = TrieNode()
for word in ["car", "cart", "care", "cat", "dog"]:
insert(root, word)
print(count_nodes(root))
print(sorted(root.children)) # the first letters
print(sorted(root.children["c"].children["a"].children))
print(root.children["c"].children["a"].is_end) # "ca" is only a prefixMistakes and edge cases.
- no end flag: without it, "ca" looks just as stored as "cat"; mark the last node of every inserted word
- making a new node every time:
node.children[ch] = TrieNode()without checking first replaces the old child and throws away every word below it - one dict for the whole trie: each node needs its own
children; a shared dict would mix up the levels - the empty word: inserting
""marks the root itself as a word end; decide whether that should be allowed - capital letters: "Cat" and "cat" are different paths; lower-case words first if they should match
Quiz
How many nodes (not counting the root) does this trie have?
class TrieNode: def __init__(self): self.children = {} # letter -> TrieNode self.is_end = False # does a word end here? def insert(root, word): node = root for ch in word: if ch not in node.children: # only make a node when the letter is missing node.children[ch] = TrieNode() node = node.children[ch] node.is_end = True def count_nodes(node): return sum(1 + count_nodes(child) for child in node.children.values()) root = TrieNode() for word in ["to", "tea", "ten", "in", "inn"]: insert(root, word) print(count_nodes(root))After inserting cart and car, which node has its end flag set for car?
- The r on the path c → a → r, which also leads on to t
- A new r made just for car
- The t at the end of cart
After inserting cart and then car, cart is no longer in the trie. Which line is wrong?
def insert(root, word): node = root for ch in word: node.children[ch] = TrieNode() node = node.children[ch] node.is_end = TrueWhy does a trie need an end flag at all?
- A word can end in the middle of a longer word's path, like car inside cart
- To count the letters
- To keep the children sorted
A trie already holds 100,000 words. How many steps does inserting a 6-letter word take?
- 6: one per letter
- About 17, log₂ of 100,000
- 100,000
Coding tasks
Using the
TrieNodeclass, writebuild_trie(words): make a root, insert every word (one node per letter, sharing nodes for shared prefixes, end flag on each word's last node) and return the root.Write
trie_size(words): how many nodes (not counting the root) a trie of these words needs. Compare it with the total number of letters to see what sharing saves.