Sub topic 10
Where tries are used in practice
This chapter assumes you can build a trie with insert, search, and prefix queries. It also assumes you know Big-O notation and the basic costs of hash maps and sorted arrays. Here we look at the problems where a trie fits, and where it doesn't.
The common thread
A trie pays off when your queries depend on the prefix of a string, not only on the whole string. Every operation walks one node per character, so cost depends on the key length L. It does not depend on how many strings are stored.
The table lists the usual applications and the trie feature each one relies on.
| Application | Query | Trie feature used |
|---|---|---|
| Autocomplete | All words starting with `ca` | Locate the prefix node, traverse its subtree |
| Spell checking | Is this word valid? Which words are close? | Exact search, pruned traversal |
| IP routing | Which route matches this address best? | Longest-prefix matching |
| Word games | Can any word start with this letter sequence? | Prefix check to stop a search early |
| Dictionary with values | Look up a definition or score by word | Values stored in nodes |
Autocomplete
A search box sends the characters typed so far. You find the node for that prefix, then collect words below it. The autocomplete method from earlier chapters does exactly this, and its limit argument keeps the traversal from visiting a huge subtree.
Real systems usually need ranked suggestions, not alphabetical ones. To get them, store a count or score in each word-ending node. You can also cache the top few suggestions at each node so a lookup does not traverse the subtree at all. The cost is extra memory and more work on updates.
Spell checking and word games
Exact search tells you whether a word is in the dictionary. For suggestions, you walk the trie while tracking how many mistakes are allowed. When a branch has already used up its allowance, you stop exploring it.
Word games such as Boggle or crosswords use the same idea. While building a candidate letter by letter, call starts_with on the partial string. If it returns False, no word can follow from here, so you abandon that path immediately. This pruning turns an exponential search into a manageable one.
def can_extend(trie, partial):
"""Return True if some dictionary word begins with `partial`."""
return trie.starts_with(partial)
def find_words(trie, letters, partial="", found=None):
"""Find dictionary words that use the given letters at most once each."""
if found is None:
found = set()
if not trie.starts_with(partial):
return found # prune: no word starts this way
if partial and trie.search(partial):
found.add(partial)
for i, ch in enumerate(letters):
rest = letters[:i] + letters[i + 1:]
find_words(trie, rest, partial + ch, found)
return foundWith a trie containing car, cat, and act, calling find_words(trie, "cart") returns {"car", "cat"} or similar words buildable from those letters. The key point is that the early return skips every permutation that begins with an impossible prefix.
Longest-prefix matching in routing
Internet routers hold a table of address prefixes, each mapped to a next hop. For a destination address, the router needs the longest stored prefix that matches. A trie over the address bits (a binary trie, with only two children per node) does this in one walk. You follow the address bit by bit and remember the last node that held a route. When the walk can go no further, that remembered route is the answer.
Production routers use compressed variants of this structure to cut memory and the number of steps. Radix trees, covered in a later chapter, are the standard form.
Other uses
- Phone keypads and T9-style input. A trie maps digit sequences to candidate words.
- URL and path routing. Web frameworks match request paths such as
/users/42/postsby splitting on/and treating each segment as one "character". - Text editors and IDEs. Symbol and identifier completion often use a trie of names in the project.
The path routing case shows that the "characters" need not be letters. Any sequence of comparable symbols works, such as words, bytes, or bits.
When not to use a trie
Choose a different structure in these cases:
- You only need exact membership. A hash set is smaller and usually faster in practice.
- Your keys are long and share few prefixes. A trie then has little sharing to exploit and spends memory on nodes.
- You need range queries over sorted keys but not prefix sharing. A sorted array or balanced tree may serve better.
Exercise
A router stores the prefixes 10.0.0.0/8 and 10.1.0.0/16, each with a different next hop. A packet arrives for 10.1.5.9. Which route should the trie return, and how does the walk find it?
Show answer
It returns the route for 10.1.0.0/16. The walk follows the address bit by bit. It passes the node for the /8 prefix and records that route, then continues to the node for the /16 prefix and records that route instead. The walk then has no further matching child, so the last recorded route, the /16 one, is the longest match.
Exercise
In the word-game search, why does calling starts_with before extending a partial string make the search faster?
Show answer
If no dictionary word begins with the partial string, no extension of it can form a word. Returning at once skips every longer string that begins with that prefix, which removes a large part of the search.