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.
#include <iostream>
int main() {
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];
std::cout << ending[edgeB[prefix]] + ending[edgeC[prefix]] << '\n';
}
2
Everyday examples
Suggest book titles
The index stores CAR and CAT. Someone types CA. Which two titles remain possible?
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?
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?
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.