Aho–Corasick: Matching a Whole Dictionary
A trie with failure links scans the text once for every pattern.
An antivirus engine checks files against thousands of byte signatures; a biologist scans a chromosome for thousands of motifs. Running a single-pattern matcher once per pattern multiplies the work by the number of patterns. Aho and Corasick (1975) fold all the patterns into one automaton that reads the text once, in time , however many patterns there are.
What you’ll learn
- Define the Aho–Corasick automaton exactly: the trie of the patterns, failure links to the longest proper suffix in the trie, and output links.
- Prove that breadth-first construction computes the failure links correctly, in total time, by a telescoping argument on depths.
- Prove that a scan reports all occurrences in time, and count the occurrences of every pattern in with the failure tree.
- Relate the automaton to KMP's prefix function and to the full DFA, and describe the frontier: dynamic, compressed, streaming and approximate dictionary matching.
The automaton
Dictionary matching. Given patterns of total length and a text of length , report every pair (position, pattern) at which a pattern occurs, and let be their number. Running KMP once per pattern costs ; restarting a walk down the trie at every text position costs for the longest pattern length . The Aho–Corasick automaton reads each text character once, in amortized time, plus per occurrence reported.
Proof. is closed under prefixes, so the suffixes of that lie in are, from longest to shortest, exactly , ending at the root: each link jumps to the longest one that is shorter. A suffix of in has the form , where is a suffix of in with a child labeled ; by induction those form the failure chain of the previous state, and the scan tries them from the longest. Finally, every pattern ending at is a suffix of in , so it is a node of the current state's failure chain, and the output links visit exactly the pattern nodes of that chain.
| Node | fail | out | Ends a pattern? |
|---|---|---|---|
| h, s, hi, her | root | none | no |
| he | root | none | yes |
| sh | h | none | no |
| his | s | none | yes |
| she | he | he | yes |
| hers | s | none | yes |
The automaton for he, she, his and hers reads the text "ushers". How many occurrences does it report?
Show the answer
3
"she" ends at the e, and its output link reports "he" at the same moment; then r takes the failure link to "he" and moves on to "her", and the final s completes "hers". Three occurrences: she at position 1, he at 2, hers at 2.
Failure links by breadth-first search
The links are computed with the automaton itself. If with root, then for the first node on the chain , root that has a child labeled , or the root if none has. This is the scanning invariant applied to followed by , restricted to proper suffixes. Children of the root fail to the root.
Every failure link points to a strictly shallower node, so processing the nodes in breadth-first order finds each link it needs already computed. Output links come in the same pass: if a pattern ends at , and otherwise.
from collections import deque
def build(patterns):
goto, fail, out, word = [{}], [0], [-1], [-1]
for idx, p in enumerate(patterns): # 1. the trie of the patterns
v = 0
for ch in p:
if ch not in goto[v]:
goto[v][ch] = len(goto)
goto.append({}); fail.append(0); out.append(-1); word.append(-1)
v = goto[v][ch]
word[v] = idx # pattern idx ends at v
order, q = [], deque(goto[0].values()) # 2. links, in breadth-first order
while q: # (depth-1 nodes keep fail = root)
u = q.popleft(); order.append(u)
for ch, v in goto[u].items():
f = fail[u]
while f and ch not in goto[f]:
f = fail[f]
fail[v] = goto[f].get(ch, 0)
out[v] = fail[v] if word[fail[v]] >= 0 else out[fail[v]]
q.append(v)
return goto, fail, out, word, orderNode 0 is the root and means "none". The list order (breadth-first order) is kept for counting occurrences later.
Let be the depth of , and the number of chain steps taken while computing it. The walk starts at , every step strictly lowers the depth, and the final goto step adds 1:
Sum along the path of one pattern , with and at depth 1. The sum telescopes, and depths are nonnegative:
Every node lies on the path of at least one pattern, so summing over all patterns counts every node's steps at least once:
With child lookups (a constant alphabet, or hashing in expectation), building the trie, the failure links and the output links takes linear time; with sorted child lists, multiply by .
Scanning in O(n + z), and counting without listing
def scan(text, patterns):
goto, fail, out, word, _ = build(patterns)
v, hits = 0, []
for i, ch in enumerate(text):
while v and ch not in goto[v]:
v = fail[v] # fall back to a shorter suffix
v = goto[v].get(ch, 0)
u = v if word[v] >= 0 else out[v]
while u > 0: # every pattern that ends at i
p = patterns[word[u]]
hits.append((i - len(p) + 1, p))
u = out[u]
return hitsscan("ushers", ["he", "she", "his", "hers"]) returns [(1, 'she'), (2, 'he'), (2, 'hers')].
Let be the depth of the state after characters, , and the number of failure links followed while reading character . Each link lowers the depth by at least 1 and the goto step raises it by at most 1:
Summing over the whole text, the depths telescope, and :
Reporting: every node visited on the output chain at position ends a different pattern, so the walk costs , where counts the occurrences ending at . In total:
Any algorithm must read the input and write its output, so with the construction, Aho–Corasick's is optimal for a constant alphabet.
Often only the number of occurrences of each pattern is needed, and then can be avoided altogether. The failure links form a tree on the trie's nodes, rooted at the root: the failure tree. By the scanning invariant, pattern ends at position exactly when the state after reading lies in the subtree of 's node in the failure tree. So count how many times the scan stands at each node, then add every node's count into its failure parent, deepest nodes first; reversed breadth-first order is such an order, since a failure link always points to a shallower node.
def count_all(text, patterns): # occurrences of every pattern, O(n + m)
goto, fail, out, word, order = build(patterns)
visits, v = [0] * len(goto), 0
for ch in text:
while v and ch not in goto[v]:
v = fail[v]
v = goto[v].get(ch, 0)
visits[v] += 1 # the state after each character
for u in reversed(order): # children before parents in the failure tree
visits[fail[u]] += visits[u]
return {patterns[word[v]]: visits[v] for v in range(len(goto)) if word[v] >= 0}On "ushershishe" this gives he: 2, she: 2, his: 1, hers: 1. The failure tree is also the gateway to harder queries, such as counting the occurrences of a pattern inside a substring of the text, by combining Euler tours of the failure tree with range data structures.
You need the number of occurrences of each of patterns (total length ) in a text of characters, and the total number of occurrences can exceed . What do you do?
- Scan with output links and count each reported occurrence
- Run KMP once for each pattern
- Record the state after each character, then sum the counts up the failure tree
- Walk the whole failure chain at every text position
Show the answer
C. Record the state after each character, then sum the counts up the failure tree
Counting visits and propagating them up the failure tree costs , about steps, however many occurrences there are. Reporting occurrences one by one costs with .
From KMP to Hyperscan: practice and the frontier
With one pattern , the trie is a path and is the node of 's longest proper border, of length , KMP's prefix function. For abababca, the failure depths along the path are 0, 0, 1, 2, 3, 4, 0, 1, exactly . Aho and Corasick generalized the failure function from a path to a tree, and their algorithm, written at Bell Labs to speed up a bibliographic search program by a factor of 5 to 10, became the basis of the original Unix fgrep.
| Method | Preprocessing | Scan | Notes |
|---|---|---|---|
| KMP once per pattern | fine for a handful of patterns | ||
| trie walked from each position | no failure links | ||
| Aho–Corasick | optimal for a constant alphabet | ||
| Aho–Corasick, full DFA | exactly transitions | small alphabets | |
| Commentz-Walter (1979) | worst case | Boyer–Moore-style shifts over a trie of reversed patterns; can skip text when patterns are long | |
| Wu–Manber (1994) | plus tables | no linear worst-case bound | hashes blocks of characters to shift; fast on large sets of long patterns |
Key takeaways
- Aho–Corasick is the trie of the patterns plus failure links (the longest proper suffix in the trie) and output links (the next pattern on the failure chain).
- After reading , the state is the longest suffix of in the trie, and the patterns ending at are the state and its output chain.
- Breadth-first construction takes and a scan , both by depth arguments: depth rises by at most 1 per step and every failure link lowers it.
- With one pattern it is KMP; precomputing every transition gives a DFA with one step per character at space.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the automaton for he, she, his and hers, where does the failure link of the node "hers" point?
- The root
- "he"
- "s"
- "h"
Show the answer
C. "s"
The proper suffixes of "hers" are "ers", "rs" and "s". Only "s" is a prefix of some pattern (of "she"), so it is the longest proper suffix in the trie.
Why does scanning a text of length follow at most failure links in total, even though one character can trigger many?
- Each pattern can trigger at most one failure link per occurrence
- The state's depth rises by at most 1 per character and falls by at least 1 per failure link, and it never goes below 0
- Failure links always point to the root, so each character follows at most one
- The patterns' total length bounds the number of failure links
Show the answer
B. The state's depth rises by at most 1 per character and falls by at least 1 per failure link, and it never goes below 0
Depth is a potential function: characters add at most to it, every failure step removes at least 1, and it starts at 0 and stays nonnegative. So the failure steps of the whole scan total at most , an amortized per character.
With a single pattern , the Aho–Corasick trie is a path. Where does the failure link of the node for point?
- To the node for , one step up
- Always to the root
- To the node for , where is KMP's prefix function
- To the node for the longest suffix of , including itself
Show the answer
C. To the node for , where is KMP's prefix function
The longest proper suffix of that is a prefix of is its longest border, of length . So Aho–Corasick with one pattern is exactly KMP, and its failure links are the prefix function.
You match 2,000 DNA motifs (alphabet A, C, G, T) of total length against a genome of bases. Which variant fits best?
- The full automaton, with precomputed for all four characters
- KMP run once per motif
- A trie walked from every genome position
- The automaton with hash-map children and failure loops
Show the answer
A. The full automaton, with precomputed for all four characters
With the table has about entries, tiny next to the genome, and every base then costs exactly one table lookup. KMP per motif would read the genome 2,000 times.
Further reading
- A. V. Aho & M. J. Corasick, "Efficient string matching: an aid to bibliographic search," Communications of the ACM 18(6) (1975), 333–340.
- D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997), chapter 3 (exact set matching).
- B. Commentz-Walter, "A string matching algorithm fast on the average" (1979).
- D. Belazzougui, "Succinct dictionary matching with no slowdown," Proceedings of CPM 2010, LNCS 6129, 88–100.
- X. Wang, Y. Hong, H. Chang, K. Park, G. Langdale, J. Hu & H. Zhu, "Hyperscan: a fast multi-pattern regex matcher for modern CPUs," Proceedings of NSDI (2019), 631–648.