Lesson contents

Tries and prefix search

A trie follows one character at a time. Words with the same beginning share a path. A separate end marker records a complete word.

Simple example

Store AB and AC. Follow A and count the two word endings below it. The prefix A is shared but is not itself a stored word.

StartA AB AC
Result2
Main.java
public class Main {
    public static void main(String[] args) {
        int[] edgeA = {1, -1, -1, -1};
        int[] edgeB = {-1, 2, -1, -1};
        int[] edgeC = {-1, 3, -1, -1};
        int[] ending = {0, 0, 1, 1};
        int prefix = edgeA[0];
        System.out.println(ending[edgeB[prefix]] + ending[edgeC[prefix]]);
    }
}
Output
2
Advertisements

Everyday examples

Suggest book titles

The index stores CAR and CAT. Someone types CA. Which two titles remain possible?

StartCAR CAT
ResultCAR CAT

Follow C then A once. The R and T branches give the two completions.

Find matching route codes

The route codes are AB, ABC and AD. Which codes begin with AB?

StartAB ABC AD
ResultAB ABC

At the B node, include its own end marker before visiting the C child.

Check a short name

The directory stores ANNA. Someone enters ANN. Is that an exact match?

StartANNA
Result∅

The prefix path exists, but there is no word ending at the second N. Keep looking only for suggestions.

Cost and limits

Following a prefix takes one step per character when child lookup is constant time. Listing matches also takes work for the results. Mark word endings separately from branches.