Mental model
Write the words car, cart, care and dog as paths from a common starting point, one step per
letter, and merge steps that agree. car, cart and care share c → a → r; dog has its own
branch. That merged shape is a trie (from retrieval, usually pronounced "try"), also called a
prefix tree:
root
/ \
c d
| |
a o
| |
r* g*
/ \
e* t* * = a word ends here
- The root stands for the empty prefix.
- Every other node stands for exactly one prefix: the characters on the path from the root to it.
- Each node knows its children (at most one per character) and whether a stored word ends there.
The end flag is essential. The node for car exists because of cart and care, but only its flag
says that car itself was inserted. Without it, a trie could not tell a stored word from a prefix of
one. The lab tags word-end nodes with the word they complete.
The four operations
All four start at the root and consume the word one character at a time. Let L be its length.
insert
node = root
for ch in word:
if node has no child ch: create it
node = child ch
if node.end: return false # already stored
node.end = true
return true
Characters shared with words already stored cost nothing new; only the unshared tail creates nodes. Inserting cart after car creates a single node.
search and startsWith
Both walk the same way and differ only in the last line:
find(prefix):
node = root
for ch in prefix:
if node has no child ch: return none
node = child ch
return node
search(word) = find(word) exists and find(word).end
startsWith(p) = find(p) exists
In the Shared prefixes preset, search("ca") is false (the path exists but no word ends at a)
while startsWith("ca") is true. search("cat") stops at a, which has no child t.
delete
Clearing the end flag is enough to make a word disappear, but it can leave a dead branch: nodes that no longer lead to any word. A tidy delete removes them on the way back up:
walk down, remembering the path; if any child is missing: return false
if not last.end: return false # the path exists, but not as a word
last.end = false
for each node on the path, from the deepest up to (not including) the root:
if node.end or node has children: stop # someone else still needs it
unlink node from its parent
return true
The Delete and prune preset shows both outcomes. Deleting cart unlinks its t node, then stops
at r, which ends car and still has the child e. Deleting car afterwards only clears a flag,
because care still runs through those nodes. Deleting ca returns false: there is a path, but no
word.
After every operation, a trie maintained this way has exactly one node per distinct non-empty prefix of the stored words. The tests in all five places (the lab's engine and four languages) check that invariant against a plain set of strings.
Cost
| Operation | Time | Notes |
|---|---|---|
| insert | O(L) | at most L new nodes |
| search, startsWith | O(L) | may stop early at a missing child |
| delete | O(L) | walk down, then at most L pruning steps |
| autocomplete: all words with prefix p | O(|p| + size of the subtree) | walk to p's node, then enumerate |
The striking part is what is missing: n, the number of stored words. Looking up a word in a trie of a million words takes the same number of steps as in a trie of ten. That assumes moving to a child is O(1), which holds for a fixed-size array of children and on average for a hash map.
Space. The node count is at most the total number of characters inserted (less when prefixes are shared), plus the root. What each node costs depends on how it stores children, and that is where tries get expensive.
Is it faster than a hash set?
For exact lookups, not necessarily. Hashing a string reads all L characters too, so a hash-set lookup is also O(L), usually with better cache behaviour: one contiguous string compared against one bucket, instead of L pointer hops through separately allocated nodes. Choose a trie when you need what a hash set cannot do cheaply:
- Prefix queries: "is anything stored under
te?", or list everything under it (autocomplete, routing tables, spell checkers). - Ordered iteration: a depth-first walk with children in alphabetical order lists the words sorted, with no sorting step.
- Longest-prefix matching: walk as far as the input allows and remember the last word end (IP routing, tokenisers).
Node layout and memory
| Children stored as | Child lookup | Memory per node | Good for |
|---|---|---|---|
| Fixed array, one slot per letter | O(1), no hashing | alphabet × pointer size, even if empty | small alphabets, dense tries |
| Hash map from character to child | O(1) expected | proportional to the actual children, plus map overhead | large alphabets (Unicode), sparse tries |
| Sorted list or array of (character, child) | O(log k) or O(k) for k children | proportional to the children | memory-tight, read-mostly tries |
With 26 slots and 8-byte references, an array node spends 208 bytes on child pointers before any other field, and most of those slots are empty in the lower levels of a typical dictionary. That is the classic trie trade-off: speed and simplicity for memory.
Common ways to cut memory:
- Compressed (radix) tries merge chains of single-child nodes into one edge labelled with a whole substring, so the node count drops to O(number of words).
- Ternary search trees store three pointers per node (less, equal, greater) and compare characters like a binary search tree.
- DAWGs / minimal automata also share common suffixes, which suits static dictionaries.
The listings use a 26-slot array in C#, Java and C++ (the direct translation of "one child per
letter") and a dict in Python, where an array of 26 Nones would cost more than the handful of
children a typical node has.
The teaching implementation
Insert, Search, StartsWith and Delete follow the pseudocode above, with search and startsWith
sharing one FindNode walk. Words are validated as non-empty lowercase a–z; anything else is
rejected rather than silently mapped to a wrong slot. The listings are the exact files the tests run:
each language replays one shared fixture of operation sequences (return values, the sorted list of
stored words and the node count after pruning), and then 300 random operation lists over the
alphabet abc against a set of strings, where startsWith is checked by scanning the whole set.
Language notes
| Language | Notes |
|---|---|
| C# | Node?[] Children = new Node?[26], index ch - 'a'. char is a UTF-16 code unit, so this layout only works for a known small alphabet. |
| Python | dict[str, _Node] children and __slots__ to keep nodes small. del parent.children[ch] prunes; an empty dict is falsy, which makes "has children" a plain truth test. |
| Java | Node[] children = new Node[26], ch - 'a'. A pruned node becomes garbage once its parent slot is null. |
| C++ | std::array<std::unique_ptr<Node>, 26>: each node owns its children, so reset() on a slot frees the whole pruned branch with no manual delete. delete is a keyword, hence the method name erase. |
Common mistakes
- No end flag, or treating "the path exists" as "the word exists":
search("ca")would be true. - Pruning too much: deleting car must not remove nodes that care still uses, and must stop at a node that ends another word.
- Deleting a prefix that is not a word and clearing nothing but returning true.
- Assuming a–z input without checking:
'A' - 'a'is negative and indexes outside the array. - Counting the trie as O(1) lookup in a comparison with a hash set; both are O(L) in the length of the key.
Edge cases
- Empty trie: every search and startsWith is false; delete returns false.
- One word that is a prefix of another (in, inn): both share nodes; deleting inn prunes only
the last
n. - Inserting a word twice: the second insert returns false and changes nothing.
- The empty string: the lab and the listings reject it. A trie could store it by setting the root's end flag, if your use case needs that.
Worked practice
1. How many nodes (root excluded) does a trie need for tea, ten, ted, to and inn?
Answer
Distinct non-empty prefixes: t, te, tea, ten, ted, to, i, in, inn, so 9 nodes. That is the node count at the end of the Prefix queries preset.
2. You store 10,000 words averaging 8 letters. What is the most nodes the trie can have, and why is the real number usually far lower?
Answer
At most 80,000 (one per character inserted) plus the root, reached only if no two words share even a first letter, which is impossible beyond 26 words over a–z. Real vocabularies share prefixes heavily, so the count is much lower.
3. After inserting car, cart and care, which nodes does delete("car") remove?
Answer
None. It clears the end flag on r, then pruning stops immediately: r still has the children t
and e.
4. How would you return every stored word that starts with a prefix p, in alphabetical order?
Answer
Walk to p's node with find(p); if it is missing, return nothing. Otherwise run a depth-first
traversal from that node, visiting children from a to z, appending the current string whenever a
node's end flag is set. The cost is O(|p|) plus the size of that subtree.
Summary
- A trie stores one node per distinct prefix; children by character, plus an end-of-word flag.
- insert, search, startsWith and delete each cost O(L) for a key of length L, independent of n.
searchneeds the end flag;startsWithonly needs the path.- delete clears the flag, then prunes upward until a node ends another word or has other children.
- Prefix queries and sorted output are the reason to choose a trie; memory is its main cost, and radix trees or hash-map children reduce it.