How to recognise
many words and questions about their starts: does a word or prefix exist, autocomplete, a word with wildcard letters, or many words to find in one grid.
How to solve problems like this
- Make a node type: children by letter (a map or an array of 26) and an end flag.
- Insert: walk from the root, add a missing child for each letter, mark the last node as an end.
- Search: walk the same way and stop at a missing letter. A word needs the end mark, a prefix does not.
- For many words in a grid, walk the trie and the grid together, so every prefix that leads nowhere stops the search early.
Variant: Search with .
The same, but the pattern has a "." that stands for any letter. A normal letter leads down one branch, a dot down all of them, so at a dot each branch is tried in turn.
- Write match(node, i): does the rest of the pattern from i fit below this node?
- Base case: at the end of the pattern, the node must carry the end mark.
- A plain letter: go to that one child, or return false if it is missing.
- A wildcard: call match on every child and return true as soon as one of them does.
Where it's used
- Routing. The Linux kernel decides where to send a packet using a trie of IP addresses (fib_trie): it walks down the bits of the address and finds the longest matching prefix.
- Web frameworks. The Go routers httprouter and Gin keep page paths such as /users/:id in a prefix tree, so the right handler is found in as many steps as the path is long, however many routes there are.
- Redis. Redis stores its Streams in a compressed prefix tree called rax.