Trie
how it works
The idea in a few sentences and three pictures, then one run, moment by moment.
A trie keeps words letter by letter down a tree. Each place holds one letter and stands for the start of a word that leads to it: c, ca, car. The top holds none. To put a word in, start at the top. For each letter, follow the place below that holds it, or make one. Then mark the last letter's place as an end. Each letter is one visit, followed or made, this page's count. The run after these pictures puts in car, cat, cart and to.
step 8 of 22
c is already below, so follow it.
visits: 1
step 9 of 22
a is already below, so follow it.
visits: 2
step 10 of 22
No t below, so make a place for it.
visits: 3
step 11 of 22
Mark this place as the end of cat.
visits: 3
step 19 of 22
No t below, so make a place for it.
visits: 1
step 20 of 22
No o below, so make a place for it.
visits: 2
step 21 of 22
Mark this place as the end of to.
visits: 2
car, cat, cart, to: 7 places, one for each start, c, ca, car, cart, cat, t and to
step 3 of 22
No c below, so make a place for it.
what it remembers to know where it is
- doing word
- 1
- letter
- c
- words stored
- 0
step 6 of 22
Mark this place as the end of car.
what it remembers to know where it is
- doing word
- 1
- letter
- not yet
- words stored
- 1
Where it says not yet, nothing is held there at that moment.
step 8 of 22
c is already below, so follow it.
what it remembers to know where it is
- doing word
- 2
- letter
- c
- words stored
- 1
step 10 of 22
No t below, so make a place for it.
what it remembers to know where it is
- doing word
- 2
- letter
- t
- words stored
- 1
step 13 of 22
c is already below, so follow it.
what it remembers to know where it is
- doing word
- 3
- letter
- c
- words stored
- 2
step 16 of 22
No t below, so make a place for it.
what it remembers to know where it is
- doing word
- 3
- letter
- t
- words stored
- 2
step 19 of 22
No t below, so make a place for it.
what it remembers to know where it is
- doing word
- 4
- letter
- t
- words stored
- 3
step 22 of 22
Done. The trie holds 4 words in 7 places below the top.
what it remembers to know where it is
- doing word
- not yet
- letter
- not yet
- words stored
- 4
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with one place that holds no letterPython line 8
- to put a word in, start at the topPython lines 9 and 10
- for each letter, follow the place below that holds itPython lines 11 and 14
- if there is none, make onePython lines 12 and 13
- mark the place of the word's last letter as an endPython line 15
- a word already marked there is already inPython line 15
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def trie(words):
"""Put each word into an empty trie, one at a time, letter by letter.
A place is a dict: each letter below it leads to the place that holds
it, and the key "" marks an end. Returns the words the trie holds, in
the order a dictionary lists them, sorting each place's letters.
"""
top = {} # one place that holds no letter
for word in words:
at = top # to put a word in, start at the top
for letter in word: # for each letter
if letter not in at: # no place below holds it,
at[letter] = {} # so make one
at = at[letter] # follow the place below
at[""] = True # mark the last letter's place as an end; twice is one word
held = []
def walk(at, start): # every end met, the letters below in order
for letter in sorted(at):
if letter == "":
held.append(start)
else:
walk(at[letter], start + letter)
walk(top, "")
return held
how it scales
How the visits grow, from ten words to a hundred thousand. From here on every word has five letters, made up, such as aaaaa and aaaab. Each of the 5 letters is one of 26. So there are 26 × 26 × 26 × 26 × 26 of them, 11,881,376: enough for every size the plot shows.
Each mark across or up is ten times the one before, a log-log plot. All three cases cost visits, so they draw one line, one mark up for each mark across: 50 visits at 10 words, 500,000 at 100,000. The words must all be different, so cannot pass 11,881,376. Up to there, every list costs exactly 5 visits a word.
visits, ten times more at each mark up
, n, ten times more at each mark to the right
- the same words reversed, sharing the fewest startssolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- words picked at randomsolid where measured by running it; dashed where its formula carries it on to ten million
- words in counting order, sharing the most startssolid where measured by running it; dashed where its formula carries it on to ten million
| visits | time | |
|---|---|---|
| 1,000 | 5,000 | about 5 microseconds |
| 100,000 | 500,000 | about 500 microseconds |
| 10,000,000 | 50,000,000 | about 50 milliseconds |
The visits are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count a trie's steps yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it puts n different
words of five letters into an empty trie, one at a time, and prints the
visits and the places made for words in counting order, for the same
words reversed, and the average over 20 lists picked at random. A visit
is one letter, its place followed or made. The counts are the same on
any computer; only the time differs.
"""
import random
def trie(words):
"""Put each word into an empty trie, one at a time, letter by letter.
A place is a dict: each letter below it leads to the place that holds
it, and the key "" marks an end. Returns the words the trie holds, in
the order a dictionary lists them, sorting each place's letters.
"""
top = {} # one place that holds no letter
for word in words:
at = top # to put a word in, start at the top
for letter in word: # for each letter
if letter not in at: # no place below holds it,
at[letter] = {} # so make one
at = at[letter] # follow the place below
at[""] = True # mark the last letter's place as an end; twice is one word
held = []
def walk(at, start): # every end met, the letters below in order
for letter in sorted(at):
if letter == "":
held.append(start)
else:
walk(at[letter], start + letter)
walk(top, "")
return held
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def word_of(k):
"""Number k, from 0, as a word of five letters: its digits counted in 26s, a for 0."""
letters = ""
for _ in range(5):
letters = LETTERS[k % 26] + letters
k //= 26
return letters
def cheapest(n):
"""The first n words in counting order, aaaaa, aaaab, aaaac and on: the fewest places."""
return [word_of(k) for k in range(n)]
def visits_and_places(words):
"""Put the words in as trie() does: one visit for each letter, followed or made, and the places made."""
top = {}
visits = made = 0
for word in words:
at = top
for letter in word:
visits += 1 # its place followed or made, a visit either way
if letter not in at:
at[letter] = {}
made += 1
at = at[letter]
return visits, made
def count(words):
"""The visits the plot counts."""
return visits_and_places(words)[0]
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>7} {'counting order':>16} {'reversed':>16} {'picked at random':>18}")
print(f"{'':>7} {'visits, places':>16} {'visits, places':>16} {'visits, places':>18}")
for n in [10, 100, 1000, 10000, 100000]:
order = cheapest(n)
backwards = [w[::-1] for w in order]
picked = [visits_and_places([word_of(k) for k in random.sample(range(26**5), n)]) for _ in range(20)]
visits = sum(v for v, _ in picked) / 20
places = sum(p for _, p in picked) / 20
a, b = visits_and_places(order), visits_and_places(backwards)
print(f"{n:>7} {a[0]:>8} {a[1]:>7} {b[0]:>8} {b[1]:>7} {visits:>9.0f} {places:>8.1f}")
extra memory, the places the sort holds beyond the row itself, ten times more at each mark up
, n, ten times more at each mark to the right
- the same words reversed, sharing the fewest startspoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
- words picked at randompoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
- words in counting order, sharing the most startspoints only, each measured by a real run, since no single formula for the extra memory of this row is worked out here
best, worst and average
Every list costs the same, 5 visits a word, in all. What sharing changes is the places made, the trie's memory. Counting order makes the fewest, reversed words the most, all between and .
A case is one kind of input, the thing the method is given, such as words in counting order, however many. A bound says how fast that case's cost grows as more words go in.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestwords in counting order, sharing the most starts | averagewords picked at random | worstthe same words reversed, sharing the fewest starts | |
|---|---|---|---|
| visits | , every list alike | , no more than the rest | |
| places made | between and , the fewest: 14 at 10 words | between and : about 48 at 10 words | between and , the most: 50 at 10 words |
| how the visits grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: a place for each different start of a word, to places
Extra memory is the room it needs on top of the input itself, while it runs.
counting order: aaaa shared, 7 places
reversed: nothing shared, 15 places
| list | letters followed | places made | visits |
|---|---|---|---|
| aaaaa, aaaab, aaaac | 8 | 7 | 15 |
| aaaaa, baaaa, caaaa | 0 | 15 | 15 |
| train, trait, sheep | 4 | 11 | 15 |
| level | counting order | reversed | the fewest any list can make | the most |
|---|---|---|---|---|
| 1 | 1 | 26 | 1 | 26 |
| 2 | 1 | 27 | 1 | 27 |
| 3 | 1 | 27 | 1 | 27 |
| 4 | 2 | 27 | 2 | 27 |
| 5 | 27 | 27 | 27 | 27 |
| in all | 32 | 134 | 32 | 134 |
where the formula comes from
Each count above, worked out line by line. Each reason names the line it uses.
the move: count a letter
the line:step 10 of 16
a is already below, so follow it.
visits: 1
step 11 of 16
a is already below, so follow it.
visits: 2
step 12 of 16
a is already below, so follow it.
visits: 3
step 13 of 16
a is already below, so follow it.
visits: 4
step 14 of 16
No b below, so make a place for it.
visits: 5
aaaab follows four a places, which aaaaa made, then makes b. 5 letters, 5 visits. why it is allowed: A put reads its word one letter at a time. At each letter it either follows the place below that holds it, or makes that place and steps into it: one visit either way.
the move: price a put
the line:step 10 of 16
a is already below, so follow it.
visits: 1
step 11 of 16
a is already below, so follow it.
visits: 2
step 12 of 16
a is already below, so follow it.
visits: 3
step 13 of 16
a is already below, so follow it.
visits: 4
step 14 of 16
a is already below, so follow it.
visits: 5
step 15 of 16
This place already marks the end of aaaaa, so it is already in.
visits: 5
aaaaa put in again follows all 5 of its letters, 5 visits, and makes nothing. Its end is already marked. why it is allowed: By line 1, one visit a letter. Marking the end reads no letter, so it is no visit. A word put in twice still costs its letters.
guess it, thenthe move: add the puts
the line:why it is allowed: is the visits of words in counting order. By line 2, each put adds 5. At 3 words, 5 + 5 + 5.
guess it, thenthe move: n lots of 5
the line:why it is allowed: Line 3 adds fives. At 3 words, 15.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4. An equals is a ceiling and a floor at once. At 3 words, 15 is at most 15, and at least 15.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 5.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, with the fixed multiple 5.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: sharing nothing changes nothing
the line:reversed: 15 places, 15 visits
Three reversed words share nothing but the top. Every letter is made, and each is still one visit. why it is allowed: Lines 1 and 2 of the first question price a put by its letters alone, whatever it shares.
the move: add the puts
the line:why it is allowed: is the visits of reversed words. By line 2 of the first question, each put adds 5.
guess it, thenthe move: n lots of 5
the line:why it is allowed: Line 2 adds fives. At 3 words, 15.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 4, with the fixed multiple 5.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, with the fixed multiple 5.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 5 and 7 bound by the same growth, .
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: every list costs the same
the line:three words picked at random letters followed places made visits quilt, maple, vivid 0 15 15 zebra, zesty, zones 3 12 15 tiger, timer, tired 4 11 15 Three lists of 3 words. Each costs 15 visits, so their average does too. why it is allowed: Lines 1 to 4 of the first question count 5 visits a word, whichever words they are.
the move: so does the average
the line:why it is allowed: is the mean visits over lists of words picked at random. By line 1, an average of equal counts is that count.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 2.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 3, with the fixed multiple 5.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 5.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, .
guess it, then
try it on small inputs: over lists of 3 different words picked at random, the average is
the move: a letter makes at most one place
the line:why it is allowed: By line 1 of the first question, each letter makes a place or follows one. A followed letter makes none.
the move: price a put
the line:train, trait, sheep: 11 places
train makes 5 and sheep 5, each at most 5. trait follows tra and i, so it makes only its t. why it is allowed: By line 1, at most one place for each of its 5 letters.
guess it, thenthe move: add the puts
the line:why it is allowed: adds the most each put can make, 5 by line 2, so the places of any words are at most .
guess it, thenthe move: n lots of 5
the line:why it is allowed: Line 3 adds fives. At 3 words, 15. Three reversed words make all 15; train, trait and sheep make 11.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 5.
guess it, thenthe move: so for the places
the line:why it is allowed: By line 3, no list of words makes more than . At 3 words, train, trait and sheep make 11, at most 15.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: each word ends at its own place
the line:step 14 of 16
No t below, so make a place for it.
visits: 5
step 15 of 16
Mark this place as the end of trait.
visits: 5
trait's last letter, t, is made below i, then marked as its end. train's end stays at n. why it is allowed: A place stands for the letters on the way down to it. Two words ending at one place would have the same letters, so they would be one word.
the move: no earlier word reaches the new end
the line:why it is allowed: Every word has 5 letters, so a put stops on level 5. In the picture, train's path stops at n on level 5 and never reaches trait's t, so trait must make that t. By line 1, no earlier word ends at a new word's end, and none can pass it.
guess it, thenthe move: the last letter is made
the line:why it is allowed: By lines 1 and 2, its end is a place no earlier word reached, so its last letter makes it.
guess it, thenthe move: add the puts
the line:why it is allowed: adds line 3's floor, 1 for each put. The first put makes all 5 of its places, so a real list makes more, as aaaaa, aaaab and aaaac make 5, 1 and 1.
guess it, thenthe move: n lots of 1
the line:why it is allowed: Line 4 adds ones. Counting order comes close, 14 places for 10 words, the 4 places of aaaa shared and 10 last letters.
guess it, thenthe move: a floor
the line:why it is allowed: By line 5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 6, with the fixed multiple 1.
guess it, thenthe move: so for the places
the line:why it is allowed: By line 4, every list of different words makes at least . At 3 words, counting order makes 7, at least 3.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
count it yourself
Count every visit as aaaaa, aaaab and aaaac go into an empty trie, in counting order. The column of letters on each level lists them level 1 first.
| step | the letters on each level | what happens | letters followed | places made | visits |
|---|---|---|---|---|---|
| 1 | Start with one place that holds no letter, and 3 words to put in. | 0 | 0 | 0 | |
| 2 | To put in aaaaa, start at the top. | 0 | 0 | 0 | |
| 3 | 1: a | No a below, so make a place for it.1: a | 0 | 1 | 1 |
| 4 | 1: a; 2: a | No a below, so make a place for it.1: a; 2: a | 0 | 2 | 2 |
| 5 | 1: a; 2: a; 3: a | No a below, so make a place for it.1: a; 2: a; 3: a | 0 | 3 | 3 |
| 6 | 1: a; 2: a; 3: a; 4: a | No a below, so make a place for it.1: a; 2: a; 3: a; 4: a | 0 | 4 | 4 |
| 7 | 1: a; 2: a; 3: a; 4: a; 5: a | No a below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a | 0 | 5 | 5 |
| 8 | 1: a; 2: a; 3: a; 4: a; 5: a | Mark this place as the end of aaaaa.1: a; 2: a; 3: a; 4: a; 5: a | 0 | 5 | 5 |
| 9 | 1: a; 2: a; 3: a; 4: a; 5: a | To put in aaaab, start at the top.1: a; 2: a; 3: a; 4: a; 5: a | 0 | 5 | 5 |
| 10 | 1: a; 2: a; 3: a; 4: a; 5: a | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a | 1 | 5 | 6 |
| 11 | 1: a; 2: a; 3: a; 4: a; 5: a | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a | 2 | 5 | 7 |
| 12 | 1: a; 2: a; 3: a; 4: a; 5: a | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a | 3 | 5 | 8 |
| 13 | 1: a; 2: a; 3: a; 4: a; 5: a | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a | 4 | 5 | 9 |
| 14 | 1: a; 2: a; 3: a; 4: a; 5: a, b | No b below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a, b | 4 | 6 | 10 |
| 15 | 1: a; 2: a; 3: a; 4: a; 5: a, b | Mark this place as the end of aaaab.1: a; 2: a; 3: a; 4: a; 5: a, b | 4 | 6 | 10 |
| 16 | 1: a; 2: a; 3: a; 4: a; 5: a, b | To put in aaaac, start at the top.1: a; 2: a; 3: a; 4: a; 5: a, b | 4 | 6 | 10 |
| 17 | 1: a; 2: a; 3: a; 4: a; 5: a, b | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b | 5 | 6 | 11 |
| 18 | 1: a; 2: a; 3: a; 4: a; 5: a, b | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b | 6 | 6 | 12 |
| 19 | 1: a; 2: a; 3: a; 4: a; 5: a, b | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b | 7 | 6 | 13 |
| 20 | 1: a; 2: a; 3: a; 4: a; 5: a, b | a is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b | 8 | 6 | 14 |
| 21 | 1: a; 2: a; 3: a; 4: a; 5: a, b, c | No c below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a, b, c | 8 | 7 | 15 |
| 22 | 1: a; 2: a; 3: a; 4: a; 5: a, b, c | Mark this place as the end of aaaac.1: a; 2: a; 3: a; 4: a; 5: a, b, c | 8 | 7 | 15 |
| 23 | 1: a; 2: a; 3: a; 4: a; 5: a, b, c | Done. The trie holds 3 words in 7 places below the top.1: a; 2: a; 3: a; 4: a; 5: a, b, c | 8 | 7 | 15 |
In all, 15 visits. The formula from section 4, , gives at : the same.
where you meet it
Two widely used programs keep tries.
Linux's routes
Linux, which runs most servers and every Android phone, keeps its IPv4 routes in a trie whose letters are an address's bits, 0 and 1. Where it can, one place tests several bits at once, as a radix tree packs letters. Looking up an address finds the longest start of it that has a route, the most exact way to send it.
source: the Linux source, net/ipv4/fib_trie.c (opens in a new tab)
Redis's streams
Redis, a database kept in memory on servers, holds each stream's records in a radix tree. For train, trait and trail, a plain trie makes 7 places and a radix tree 4, as nothing branches before i.
source: the Redis source, src/rax.c (opens in a new tab), its radix tree, and src/stream.h (opens in a new tab), whose stream holds a radix tree
four routes, written in bits
a trie: 7 places
a radix tree: 4 places
what is used instead
To ask only whether a word is in, a hash table of the words is the usual choice. It keeps a slot for each word and some to spare, not a place for each letter. Reach for a trie when you ask by a word's start: every word beginning with tra, or the longest start of an address.
how it compares
Two ways to keep words, set side by side by what they answer and what they hold.
| way | is one word in | every word starting with given letters | extra memory |
|---|---|---|---|
| a trie | walk down its letters: at most 5 visits for a word of five | walk down the start, then list the ends below it | to places, a letter each |
| a hash table of the words | work out its slot from its letters, and look there | read every word and test each one | a slot for each word, and some to spare |