Skip to content

Tries: a tree of prefixes

Working knowledgeUnder the hood

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.

Hash set of wordsEvery word checkedExact lookup is fast, but a prefix query means testing w.startswith("ca") against all n words.
TrieOne step per letterWalk two edges to the 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.

Each node is labelled under it with the prefix it stands for
Trie for car, cat, cart, do
·
cc
aca
rcar·end
tcart·end
tcat·end
dd
odo·end

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.

Inserting car, cat, cart, do
Step 1 of 9
TrieEmpty
Words stored
Empty
  • node just created
  • node followed

Nothing exists yet: no nodes, no words.

none yet inserting

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.

All words that start with ca
Step 1 of 6
Trie
·
c
a
rend
tend
tend
d
oend
Matches
Empty
  • node visited now
  • on the prefix path
  • collected

Find every word starting with ca. Nothing has been read yet.

ca prefix

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.

trie.py
class Node:
def __init__(self):
self.children = {} # one entry per next character
self.end = False # a word stops here
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
node = self.root
for ch in word:
node = node.children.setdefault(ch, Node())
node.end = True
def _walk(self, prefix):
main.py
from trie import Trie
t = Trie()
for w in ["car", "cat", "cart", "do"]:
t.insert(w)
print(t.starts_with("ca"))
print(t.starts_with("cu"))
print(t.contains("ca"), t.contains("car"))
Text
['car', 'cart', 'cat']
[]
False True

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

L is the length of the word or prefix; m is the number of matches
OperationTrieHash setSorted list + binary search
Insert a wordO(L)O(L) to hashO(n) to shift items
Is this word stored?O(L)O(L) on averageO(L log n)
Words with this prefixO(L) + size of the subtreeO(n · L), scan everythingO(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.

08 Check yourself

Question

You insert tea, ten and to into an empty trie. How many nodes are there, not counting the root?

Question

The trie holds car and cart only. What does contains("cart") do?

Question

Why can a hash set not answer "which words start with ca?" quickly?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?