Building a trie
A trie is a tree for strings. Each node keeps kids, a dict from one letter to a child node, and end, a flag. The root stands for the empty string. Walking down spells a word, one letter per level.
insert(root, "cat"): the root has no 'c' child, so line 5 makes one, then line 6 steps down to it. Same for 'a' and 't'. Line 7 sets end = True on the last node: the gold dot means a word ends here.
insert "car": 'c' and 'a' already exist, so line 6 just steps down them. Only 'r' is new. Words that start the same share one path, so the prefix "ca" is stored once.
insert "cart": c, a and r all exist; only 't' is new, under "car". The "car" node keeps its gold dot, so both words are stored. An end flag can sit in the middle of a path.
insert "dog": the root has no 'd' child, so a second branch starts at the root: lines 5 and 6 for each letter, line 7 at the end. Four words, 13 letters in total, but only 8 nodes below the root: shared prefixes saved 5.
Looking words up
find(root, "cart") follows one link per letter (line 14): c, a, r, t. 4 hops, and the node it lands on has end = True, so "cart" is stored. The "dog" branch is never looked at.
find "cap": c and a are there, but the "ca" node has no 'p' child. Line 13 returns None after checking 3 letters. A miss can stop sooner, even at the first letter.
find "ca" does reach a node, but its end flag is False: "ca" is the start of stored words, not a word itself. So a word search needs both: the node exists and its end is True.
Prefixes and cost
Words starting with "ca": walk to the "ca" node, then visit everything below it. Each gold dot is a word: car, cart, cat. Visiting kids in sorted letter order lists them alphabetically. Autocomplete works this way.
Line 11 loops once per letter: O(L) for a string of length L, however many words are stored. A balanced search tree of n strings needs about log₂ n comparisons instead, and each one may read up to L letters.
What happens
;; step 1/10 · trie-idea
class Node:
def __init__(self):
self.kids = {} # letter -> child Node
self.end = False # True if a word ends here
root = Node() # the empty string ""
child of node p under letter ch = the prefix p + ch
words to store: "cat", "car", "cart", "dog"
Here each node's kids is a Python dict, so checking one letter is an expected O(1) lookup. Sedgewick and Wayne's R-way trie uses an array of R links per node instead (R = 256 for extended ASCII): faster to index, but most links are empty. Sedgewick and Wayne: a search hit must examine all L characters, while a search miss can stop at the first mismatch. A balanced BST does O(log n) comparisons (MIT 6.006: operations are O(h) and h should be O(lg n)), and comparing two strings can read up to L characters.