Skip to content

Trie

storing

Level 2 of 3

Also called Prefix tree and Digital tree.

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.

  1. step 8 of 22

    car

    c is already below, so follow it.

    visits: 1

  2. step 9 of 22

    car

    a is already below, so follow it.

    visits: 2

  3. step 10 of 22

    cart

    No t below, so make a place for it.

    visits: 3

  4. step 11 of 22

    cart

    Mark this place as the end of cat.

    visits: 3

Operation 2 puts cat in after car. It follows c and a, which car made, then makes t: 3 visits. Then it marks t as an end.
  1. step 19 of 22

    carttt

    No t below, so make a place for it.

    visits: 1

  2. step 20 of 22

    carttto

    No o below, so make a place for it.

    visits: 2

  3. step 21 of 22

    carttto

    Mark this place as the end of to.

    visits: 2

No place below the top holds t, so to makes both its places, 2 visits. It shares nothing with the words before it.
  • carttto

    car, cat, cart, to: 7 places, one for each start, c, ca, car, cart, cat, t and to

The trie the run below ends with. The blue places are ends; cart's t hangs below car's r.
Words that share their start: 8 moments of its 22 steps, the steps between them left for the watch page
  1. step 3 of 22

    01c

    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

    watch from here

  2. step 6 of 22

    01c2a3r

    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.

    watch from here

  3. step 8 of 22

    01c2a3r

    c is already below, so follow it.

    what it remembers to know where it is
    doing word
    2
    letter
    c
    words stored
    1

    watch from here

  4. step 10 of 22

    01c2a3r4t

    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

    watch from here

  5. step 13 of 22

    01c2a3r4t

    c is already below, so follow it.

    what it remembers to know where it is
    doing word
    3
    letter
    c
    words stored
    2

    watch from here

  6. step 16 of 22

    01c2a3r5t4t

    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

    watch from here

  7. step 19 of 22

    01c2a3r5t4t6t

    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

    watch from here

  8. step 22 of 22

    01c2a3r5t4t6t7o

    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.

    watch from here

the steps, in plain words
  1. start with one place that holds no letterPython line 8
  2. to put a word in, start at the topPython lines 9 and 10
  3. for each letter, follow the place below that holds itPython lines 11 and 14
  4. if there is none, make onePython lines 12 and 13
  5. mark the place of the word's last letter as an endPython line 15
  6. 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 5n5n visits, so they draw one line, one mark up for each mark across: 50 visits at 10 words, 500,000 at 100,000. The nn words must all be different, so nn cannot pass 11,881,376. Up to there, every list costs exactly 5 visits a word.

visits, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, 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
what reversed words cost, at a billion visits a second
nnvisitstime
1,0005,000about 5 microseconds
100,000500,000about 500 microseconds
10,000,00050,000,000about 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

102104106101102103104105106107101102103104105106101102103104105106107101102103104105106101102103104105106107

nn, 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, 5n5n in all. What sharing changes is the places made, the trie's memory. Counting order makes the fewest, reversed words the most, all between nn and 5n5n.

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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestwords in counting order, sharing the most startsaveragewords picked at randomworstthe same words reversed, sharing the fewest starts
visits5n5n5n5n, every list alike5n5n, no more than the rest
places madebetween nn and 5n5n, the fewest: 14 at 10 wordsbetween nn and 5n5n: about 48 at 10 wordsbetween nn and 5n5n, the most: 50 at 10 words
how the visits grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)Θ(n)\Theta(n)Θ(n)\Theta(n)
ceiling, OOO(n)O(n)O(n)O(n)O(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)Ω(n)\Omega(n)Ω(n)\Omega(n)

extra memory: a place for each different start of a word, nn to 5n5n places

Extra memory is the room it needs on top of the input itself, while it runs.

  • aaaaabc

    counting order: aaaa shared, 7 places

  • aaaaabaaaacaaaa

    reversed: nothing shared, 15 places

Three words two ways, 15 visits each. Counting order shares its first four letters; reversed words share nothing but the top.
listletters followedplaces madevisits
aaaaa, aaaab, aaaac8715
aaaaa, baaaa, caaaa01515
train, trait, sheep41115
Each list costs 15 visits, 5 a word. Only the places differ.
levelcounting orderreversedthe fewest any list can makethe most
1126126
2127127
3127127
4227227
527272727
in all3213432134
Counting order makes the fewest places any list can, reversed words the most, level by level. Here are 27 words, aaaaa to aaaaz and aaaba, and the same back to front. A place has at most 26 below it, so 27 ends need 2 places on level 4. A level holds at most one place a word, and level 1 at most 26.

where the formula comes from

Each count above, worked out line by line. Each reason names the line it uses.

Why do nn words in counting order cost 5n5n visits?
  1. the move: count a letter

    the line:
    each letter is one visit,followed or made\begin{gathered} \text{each letter is one visit,} \\ \text{followed or made} \end{gathered}
    1. step 10 of 16

      aaaaa

      a is already below, so follow it.

      visits: 1

    2. step 11 of 16

      aaaaa

      a is already below, so follow it.

      visits: 2

    3. step 12 of 16

      aaaaa

      a is already below, so follow it.

      visits: 3

    4. step 13 of 16

      aaaaa

      a is already below, so follow it.

      visits: 4

    5. step 14 of 16

      aaaaab

      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.

  2. the move: price a put

    the line:
    a word of 5 letterscosts 5 visits\begin{gathered} \text{a word of 5 letters} \\ \text{costs 5 visits} \end{gathered}
    1. step 10 of 16

      aaaaa

      a is already below, so follow it.

      visits: 1

    2. step 11 of 16

      aaaaa

      a is already below, so follow it.

      visits: 2

    3. step 12 of 16

      aaaaa

      a is already below, so follow it.

      visits: 3

    4. step 13 of 16

      aaaaa

      a is already below, so follow it.

      visits: 4

    5. step 14 of 16

      aaaaa

      a is already below, so follow it.

      visits: 5

    6. step 15 of 16

      aaaaa

      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.

  3. the move: add the puts

    the line:
    B=5+5+⋯+5B = 5 + 5 + \dots + 5

    why it is allowed: BB is the visits of nn words in counting order. By line 2, each put adds 5. At 3 words, 5 + 5 + 5.

  4. the move: n lots of 5

    the line:
    B=5nB = 5n

    why it is allowed: Line 3 adds nn fives. At 3 words, 15.

  5. the move: a ceiling

    the line:
    B≤5nB \le 5n

    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.

  6. the move: read it as a bound

    the line:
    B∈O(n)B \in O(n)

    why it is allowed: By line 5, with the fixed multiple 5.

  7. the move: a floor

    the line:
    B≥5nB \ge 5n

    why it is allowed: By line 4 again.

  8. the move: read it as a bound

    the line:
    B∈Ω(n)B \in \Omega(n)

    why it is allowed: By line 7, with the fixed multiple 5.

  9. the move: ceiling and floor together

    the line:
    B∈Θ(n)B \in \Theta(n)

    why it is allowed: Lines 6 and 8 bound BB by the same growth, nn.

try it with a small nn: at n=3n = 3, line 3 gives B=15B = 15, which you can work out by hand

Why do reversed words cost the same 5n5n visits?
  1. the move: sharing nothing changes nothing

    the line:
    a put costs one visita letter, shared or not\begin{gathered} \text{a put costs one visit} \\ \text{a letter, shared or not} \end{gathered}
    • aaaaabaaaacaaaa

      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.

  2. the move: add the puts

    the line:
    W=5+5+⋯+5W = 5 + 5 + \dots + 5

    why it is allowed: WW is the visits of nn reversed words. By line 2 of the first question, each put adds 5.

  3. the move: n lots of 5

    the line:
    W=5nW = 5n

    why it is allowed: Line 2 adds nn fives. At 3 words, 15.

  4. the move: a ceiling

    the line:
    W≤5nW \le 5n

    why it is allowed: By line 3.

  5. the move: read it as a bound

    the line:
    W∈O(n)W \in O(n)

    why it is allowed: By line 4, with the fixed multiple 5.

  6. the move: a floor

    the line:
    W≥5nW \ge 5n

    why it is allowed: By line 3 again.

  7. the move: read it as a bound

    the line:
    W∈Ω(n)W \in \Omega(n)

    why it is allowed: By line 6, with the fixed multiple 5.

  8. the move: ceiling and floor together

    the line:
    W∈Θ(n)W \in \Theta(n)

    why it is allowed: Lines 5 and 7 bound WW by the same growth, nn.

try it with a small nn: at n=3n = 3, line 2 gives W=15W = 15, which you can work out by hand

Why do words picked at random cost 5n5n visits on average?
  1. the move: every list costs the same

    the line:
    every list of n wordscosts 5n visits\begin{gathered} \text{every list of } n \text{ words} \\ \text{costs } 5n \text{ visits} \end{gathered}
    three words picked at randomletters followedplaces madevisits
    quilt, maple, vivid01515
    zebra, zesty, zones31215
    tiger, timer, tired41115
    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.

  2. the move: so does the average

    the line:
    A=5nA = 5n

    why it is allowed: AA is the mean visits over lists of words picked at random. By line 1, an average of equal counts is that count.

  3. the move: a ceiling

    the line:
    A≤5nA \le 5n

    why it is allowed: By line 2.

  4. the move: read it as a bound

    the line:
    A∈O(n)A \in O(n)

    why it is allowed: By line 3, with the fixed multiple 5.

  5. the move: a floor

    the line:
    A≥5nA \ge 5n

    why it is allowed: By line 2 again.

  6. the move: read it as a bound

    the line:
    A∈Ω(n)A \in \Omega(n)

    why it is allowed: By line 5, with the fixed multiple 5.

  7. the move: ceiling and floor together

    the line:
    A∈Θ(n)A \in \Theta(n)

    why it is allowed: Lines 4 and 6 bound AA by the same growth, nn.

try it on small inputs: over lists of 3 different words picked at random, the average is A=15A = 15

Why can nn words of five letters make no more than 5n5n places?
  1. the move: a letter makes at most one place

    the line:
    each letter makesat most 1 place\begin{gathered} \text{each letter makes} \\ \text{at most 1 place} \end{gathered}

    why it is allowed: By line 1 of the first question, each letter makes a place or follows one. A followed letter makes none.

  2. the move: price a put

    the line:
    a word of 5 letters makesat most 5 places\begin{gathered} \text{a word of 5 letters makes} \\ \text{at most 5 places} \end{gathered}
    • sheeptraint

      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.

  3. the move: add the puts

    the line:
    U=5+5+⋯+5U = 5 + 5 + \dots + 5

    why it is allowed: UU adds the most each put can make, 5 by line 2, so the places of any nn words are at most UU.

  4. the move: n lots of 5

    the line:
    U=5nU = 5n

    why it is allowed: Line 3 adds nn fives. At 3 words, 15. Three reversed words make all 15; train, trait and sheep make 11.

  5. the move: a ceiling

    the line:
    U≤5nU \le 5n

    why it is allowed: By line 4.

  6. the move: read it as a bound

    the line:
    U∈O(n)U \in O(n)

    why it is allowed: By line 5, with the fixed multiple 5.

  7. the move: so for the places

    the line:
    the places made are atmost U, so they areO(n) too\begin{gathered} \text{the places made are at} \\ \text{most } U \text{, so they are} \\ O(n) \text{ too} \end{gathered}

    why it is allowed: By line 3, no list of nn words makes more than UU. At 3 words, train, trait and sheep make 11, at most 15.

try it with a small nn: at n=3n = 3, line 3 gives U=15U = 15, which you can work out by hand

Why must nn different words of five letters make at least nn places?
  1. the move: each word ends at its own place

    the line:
    two different wordsend at two places\begin{gathered} \text{two different words} \\ \text{end at two places} \end{gathered}
    1. step 14 of 16

      traint

      No t below, so make a place for it.

      visits: 5

    2. step 15 of 16

      traint

      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.

  2. the move: no earlier word reaches the new end

    the line:
    no earlier word passesthrough a new word’s end\begin{gathered} \text{no earlier word passes} \\ \text{through a new word's end} \end{gathered}

    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.

  3. the move: the last letter is made

    the line:
    a new word makesat least 1 place\begin{gathered} \text{a new word makes} \\ \text{at least 1 place} \end{gathered}

    why it is allowed: By lines 1 and 2, its end is a place no earlier word reached, so its last letter makes it.

  4. the move: add the puts

    the line:
    F=1+1+⋯+1F = 1 + 1 + \dots + 1

    why it is allowed: FF 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.

  5. the move: n lots of 1

    the line:
    F=nF = n

    why it is allowed: Line 4 adds nn ones. Counting order comes close, 14 places for 10 words, the 4 places of aaaa shared and 10 last letters.

  6. the move: a floor

    the line:
    F≥nF \ge n

    why it is allowed: By line 5.

  7. the move: read it as a bound

    the line:
    F∈Ω(n)F \in \Omega(n)

    why it is allowed: By line 6, with the fixed multiple 1.

  8. the move: so for the places

    the line:
    the places made are atleast F, so they areΩ(n) too\begin{gathered} \text{the places made are at} \\ \text{least } F \text{, so they are} \\ \Omega(n) \text{ too} \end{gathered}

    why it is allowed: By line 4, every list of nn different words makes at least FF. At 3 words, counting order makes 7, at least 3.

try it with a small nn: at n=3n = 3, line 4 gives F=3F = 3, 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.

aaaaa, aaaab, aaaac, every step written down
stepthe letters on each levelwhat happensletters followedplaces madevisits
1Start with one place that holds no letter, and 3 words to put in.000
2To put in aaaaa, start at the top.000
31: aNo a below, so make a place for it.1: a011
41: a; 2: aNo a below, so make a place for it.1: a; 2: a022
51: a; 2: a; 3: aNo a below, so make a place for it.1: a; 2: a; 3: a033
61: a; 2: a; 3: a; 4: aNo a below, so make a place for it.1: a; 2: a; 3: a; 4: a044
71: a; 2: a; 3: a; 4: a; 5: aNo a below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a055
81: a; 2: a; 3: a; 4: a; 5: aMark this place as the end of aaaaa.1: a; 2: a; 3: a; 4: a; 5: a055
91: a; 2: a; 3: a; 4: a; 5: aTo put in aaaab, start at the top.1: a; 2: a; 3: a; 4: a; 5: a055
101: a; 2: a; 3: a; 4: a; 5: aa is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a156
111: a; 2: a; 3: a; 4: a; 5: aa is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a257
121: a; 2: a; 3: a; 4: a; 5: aa is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a358
131: a; 2: a; 3: a; 4: a; 5: aa is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a459
141: a; 2: a; 3: a; 4: a; 5: a, bNo b below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a, b4610
151: a; 2: a; 3: a; 4: a; 5: a, bMark this place as the end of aaaab.1: a; 2: a; 3: a; 4: a; 5: a, b4610
161: a; 2: a; 3: a; 4: a; 5: a, bTo put in aaaac, start at the top.1: a; 2: a; 3: a; 4: a; 5: a, b4610
171: a; 2: a; 3: a; 4: a; 5: a, ba is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b5611
181: a; 2: a; 3: a; 4: a; 5: a, ba is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b6612
191: a; 2: a; 3: a; 4: a; 5: a, ba is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b7613
201: a; 2: a; 3: a; 4: a; 5: a, ba is already below, so follow it.1: a; 2: a; 3: a; 4: a; 5: a, b8614
211: a; 2: a; 3: a; 4: a; 5: a, b, cNo c below, so make a place for it.1: a; 2: a; 3: a; 4: a; 5: a, b, c8715
221: a; 2: a; 3: a; 4: a; 5: a, b, cMark this place as the end of aaaac.1: a; 2: a; 3: a; 4: a; 5: a, b, c8715
231: a; 2: a; 3: a; 4: a; 5: a, b, cDone. The trie holds 3 words in 7 places below the top.1: a; 2: a; 3: a; 4: a; 5: a, b, c8715

In all, 15 visits. The formula from section 4, 5n5n, gives B=15B = 15 at n=3n = 3: 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

  • 01011

    four routes, written in bits

An address starting 1011 walks down 1, 10 and 101. The longest route on its way is 101.
  • trailnt

    a trie: 7 places

  • trailnt

    a radix tree: 4 places

The same three words, 7 places against 4. The radix tree keeps trai in one place.

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 nn words, set side by side by what they answer and what they hold.

wayis one word inevery word starting with given lettersextra memory
a triewalk down its letters: at most 5 visits for a word of fivewalk down the start, then list the ends below itnn to 5n5n places, a letter each
a hash table of the wordswork out its slot from its letters, and look thereread every word and test each onea slot for each word, and some to spare
Both answer whether a word is in. Only the trie answers a question about a word's start by walking to it.