Tries: a tree of prefixes
A hash set tells you whether a word is stored, but not which words start with ca. A trie stores words letter by letter along the edges of a tree, so every word with the same prefix sits under the same node.
01 Every word that starts with ca
A search box shows suggestions as you type. After ca it wants every stored word that starts with ca, and it wants them before the next key press. The question is not "is this word stored?" but "which stored words begin with this?"
A hash set is the usual answer to "is it stored?", and it cannot help here. It hashes the whole word, so car and cart land in unrelated buckets. Nothing in the set knows they share a beginning.
w.startswith("ca") against all n words.ca node. Every match lies below it, and nothing else is touched.02 One letter per edge
A trie (from retrieval, usually said "try") is a tree where each edge carries one character. The root is the empty string. Following edges spells out a prefix, so each node stands for exactly one prefix, and words that share a beginning share that path.
The path from the root spells the prefix. ·end marks a node where a whole word stops.
Two things follow. All words starting with ca sit in the subtree under the ca node. And a node needs a flag saying whether a word ends there, because car ends at a node that also has a child.
03 Insert: walk, and add what is missing
Insert walks from the root one letter at a time. If the child for that letter exists, follow it; if not, create it. At the last letter, set the end flag.
- node just created
- node followed
Nothing exists yet: no nodes, no words.
Insert costs one step per letter of the word, whatever the number of words already stored. The trie never compares whole words with each other.
04 Prefix lookup: walk down, then collect
A prefix query has two phases. Walk the prefix like an insert that never creates nodes. Then walk the whole subtree below and gather every node that has the end flag.
- node visited now
- on the prefix path
- collected
Find every word starting with ca. Nothing has been read yet.
A miss is even cheaper. For cu, the walk reaches c, finds no u child, and stops after one step with no matches. An exact lookup of ca walks the same two edges and then checks the flag: it is not set, so ca is a prefix but not a stored word.
05 The code
Each node is a dict from character to child, plus the end flag. Python dicts keep insertion order, which is why the matches come out in the order the children were added.
That is the real output of python3 main.py on Python 3.14. Sort the children (or store them in a fixed array of 26 for lowercase letters) if you want matches in alphabetical order.
06 What it costs, and where memory goes
| Operation | Trie | Hash set | Sorted list + binary search |
|---|---|---|---|
| Insert a word | O(L) | O(L) to hash | O(n) to shift items |
| Is this word stored? | O(L) | O(L) on average | O(L log n) |
| Words with this prefix | O(L) + size of the subtree | O(n · L), scan everything | O(L log n) to find the start, then read m in a row |
The price is memory. Every letter that is not shared becomes its own node, and in CPython each node here is an object plus a dict, typically a few hundred bytes in all, to hold one character. A list of a million short words can easily take several times its raw size.
Two common answers: a radix tree (compressed trie) merges chains of single-child nodes into one edge labelled with a whole string, and a sorted array with binary search gives prefix ranges with no nodes at all. Typeahead systems also cap the work for short prefixes: typically each node stores its top few suggestions, so c does not need a walk of every word starting with c.
07 When it bites
return node is not NoneForgetting the end flagWithout node.end, contains("ca") returns True because the ca node exists. A node existing only proves a prefix exists.t.starts_with("a")Short prefixes return huge subtreesOne letter can match a large share of all words. Stop after k matches, or store ranked suggestions on the nodes, instead of collecting the whole subtree.node.children.pop(ch)Deleting a word carelesslyClear the end flag first. Remove nodes only on the way back up, and only while they have no children and no end flag of their own; removing car's r would also delete cart.t.insert("Café")Case and UnicodeC and c are different edges, and é can be one code point or two. Normalise text (for example lower-case plus NFC) before inserting and before searching.