Info & Theory
Aho–Corasick finds every occurrence of several patterns
in a text in one linear pass, by combining a
trie of all patterns with failure
links that generalize the idea behind the
single-pattern KMP algorithm.
1. Trie construction
Insert every pattern into a shared trie rooted at
node 0. Each node represents the string spelled
out by the path from the root; a node is marked as an
output node if that path equals one of the
patterns.
2. Failure links (BFS)
For every node v reached from parent
u via character c, the
failure link f(v) points to the node
representing the longest proper suffix of v's
string that is also a prefix of some pattern (i.e. also a
node in the trie). Failure links are computed with a
BFS over the trie, level by level: root's
children get f = root; for a deeper child
reached from u via c, walk
u's failure chain until a node with a
goto edge on c is found (or fall
back to root).
3. Output / dictionary suffix links
A node can represent a suffix of several matched patterns at
once, so each node's effective match set is its own
outputs plus all outputs reachable by following
failure links up to the root — the dictionary suffix
chain. Precomputing this merged set (or walking it live)
lets the scanner report every pattern ending at a position
without missing overlapping matches.
4. Scanning
Feed the text one character at a time. From the current state, follow a trie edge if one exists; otherwise repeatedly follow failure links until an edge is found or the root is reached. After each transition, report the merged output set at the new state as matches ending at that position.
Complexity
Building the trie and failure links costs
O(m) where m is the total length of
all patterns; scanning the text costs O(n) where
n is the text length. Reporting all matches costs
O(z) where z is the number of
matches, giving a total of O(n + m + z).