Scan a text for a whole dictionary of words at once. Running a separate search per word is slow; Aho-Corasick stitches the patterns into a single trie, adds failure links that say where to fall back on a mismatch, and walks the text one character at a time — never re-reading a character, firing every match as it goes. O(text + matches).
O(text + patterns + matches) · one pass · multi-pattern
the trie
All patterns share prefixes in one tree; a path spells a pattern prefix.
goto edge
The next character moves you down the trie — a normal transition.
failure link
On a mismatch, jump to the longest suffix that's still a pattern prefix.
output
A node fires every pattern that ends there — including via failure links.
aho.js — trie + failure links, scanned in one pass
Ready
Patterns he · she · his · hers built into a trie (green goto edges) with failure links (red, dashed). Press Step to scan the text ushers: each character either follows a goto edge deeper, or — when there's no edge — follows failure links back until one fits. Double-ringed nodes fire matches.
0
state
–
text pos
0
matches
How it works
The trie alone can only match patterns that start where you happen to be. The insight is the failure link: when the current character has no goto edge, the longest suffix of what you've matched so far might still begin another pattern — so you slide to that node instead of throwing away progress and restarting at the root. It's exactly KMP's fallback, generalized from one pattern to a tree of them.
1
Build the trie
Insert every pattern; shared prefixes share a path. Mark each pattern's final node with its output.
2
Wire failure links (BFS)
For each node, its failure link points to the node spelling the longest proper suffix that is also a trie prefix — computed level by level from the root.
3
Scan the text once
For each character: if a goto edge exists, take it; otherwise follow failure links until one does (or reach the root). Never move the text cursor backward.
✓
Report outputs
At each state, emit every pattern ending there. Because outputs chain along failure links, one position can fire several matches at once (e.g. she also ends he).
Scan
O(n + z)
Build
O(Σ|pattern|)
n
text length
z
# matches
The code
# goto[state][char], fail[state], output[state] already builtdef search(text):
s = 0
for i, c in enumerate(text):
while s != 0 and c not in goto[s]:
s = fail[s] # fall back on mismatch
s = goto[s].get(c, 0) # take the edge (or reset to root)for pat in output[s]: # fire every match ending here
report(pat, end=i)
# failure links, by BFS (output[] merges along the way)for node in bfs_order:
f = fail[parent]; while f and c not in goto[f]: f = fail[f]
fail[node] = goto[f].get(c, 0)
output[node] += output[fail[node]]
The while loop looks quadratic but isn't: across the whole scan the state depth rises by at most one per character and each failure jump lowers it, so total work is linear in the text length. Merging output[fail[node]] into output[node] at build time is what lets a single state report nested matches like he inside she without walking the failure chain during the scan.
Quick check
1. On a character with no goto edge, why follow the failure link instead of restarting at the root?
Right — the failure link points to the longest suffix that's also a prefix of some pattern, so partial progress is preserved and the text cursor never moves backward. That's what keeps the scan linear.
2. Scanning ushers, reaching the node for she fires two matches. Why?
Right — he is a suffix of she, so the "she" node's output set (merged from its failure link) includes he. One position, two matches: she@1–3 and he@2–3.
FAQ
What problem does it solve?
Finding all occurrences of many patterns in a text in one linear pass, rather than searching for each pattern separately.
What is a failure link?
A pointer to the node spelling the longest proper suffix of the current match that is also a prefix of some pattern — where to fall back on a mismatch.
How does it relate to KMP?
It's the multi-pattern generalization of KMP: the prefix-function fallback becomes failure links over a trie of patterns.
Where is it used?
Intrusion detection, antivirus signatures, spam/profanity filters, and DNA motif search — anywhere a stream is matched against a fixed dictionary.
The picture: one trie, with failure links back
The 10-node trie of the four patterns (the root plus 9 prefixes). Highlighted: the path for she, and he, which the failure link from she reaches. Arriving at she therefore reports both words without any second search. Failure links computed by code: sh→h, she→he, his→s, hers→s; every other node falls back to the root.
Worked example, step by step
Patterns he, she, his, hers, text ushers. The cursor moves one character per row and never goes back. “Failure hops” counts how many failure links were followed before an edge for the character was found. Outputs list every pattern that ends at the new state, including those inherited along failure links.
Pos
Char
Failure hops
New state
Matches reported
0
u
0
root
—
1
s
0
s
—
2
h
0
sh
—
3
e
0
she
she (starts at 1), he (starts at 2)
4
r
1
her
—
5
s
0
hers
hers (starts at 2)
Three matches come out of a six-character scan: he@2, hers@2, she@1. Position 3 is the instructive row: the state she reports two words, because its failure link points at he, which is itself a pattern. At position 4 the character r has no edge out of she, so the scan takes one failure hop to he and finds r there, landing on her. That is the “don’t throw away progress” step: the he in she is the start of hers. The whole scan used 1 failure hop in total, for 6 characters and 4 patterns.
Complexity and trade-offs
Case
Time
Space
Why
Aho–Corasick
O(n + Σ|p| + z)
O(Σ|p|·σ) dense, O(Σ|p|) sparse
Build the trie and links once, then one pass. n is text length, z the number of matches, σ the alphabet size.
One KMP scan per pattern
O(k·n + Σ|p|)
O(max |p|)
k patterns means k passes over the text. Fine for 4 patterns, slow for 100,000.
Naive search per pattern
O(k·n·m)
O(1)
Worst case when patterns almost match everywhere.
Rabin–Karp with a hash set
O(n) expected per length
O(k)
Good when all patterns have the same length; one rolling hash per distinct length otherwise.
Index the text (suffix array)
O(n log n) build, O(m log n) per query
O(n)
Wins when the text is fixed and the patterns change; Aho–Corasick wins when the patterns are fixed and text streams past.
Why the scan stays linear: each character moves you down at most one trie level, and every failure hop moves you up at least one, so total hops cannot exceed the characters read. The price is memory. A table indexed by every possible byte for a dictionary of 1,000,000 trie nodes holds 256 million entries, about 1 GB at 4 bytes each; real implementations store sparse edges or compress the alphabet. Matches are the other cost: a dictionary of nested words (a, aa, aaa, …) on a text of all as can report far more than n matches, so z can dominate.
Common mistakes
Not inheriting outputs along failure links
Without merging out[fail[v]] into out[v] the scan of ushers reports only hers@2, she@1 and misses he inside she. Nested patterns are exactly where the data structure is meant to help.
Building failure links out of breadth-first order
A node’s link is found by walking its parent’s links, so every shallower node must be finished first. A depth-first build reads links that are still 0 and silently links nodes to the root, losing matches that cross pattern boundaries.
A fall-back loop that never ends at the root
The loop must be while state != 0 and char not in goto[state]. Without the state != 0 guard, a character that appears in no pattern keeps following the root’s link, which is the root, forever.
Reporting the end index as the start
The scan knows where a match ends. The start is i - len(p) + 1. Reporting i gives hers@5 for a match that starts at 2 in ushers.
Dense tables over a large alphabet
A 256-wide table per node is simple and fast for small dictionaries and a memory problem for large ones: a million-node trie needs about 1 GB. For Unicode text, use sparse edges or work on UTF-8 bytes.
Where this shows up
fgrep and multi-keyword grep
The original paper (Aho and Corasick, 1975) was written to speed up a bibliographic search for many keywords at once, and the idea became the Unix fgrep. Searching for a list of fixed strings (grep -F -f words.txt) is the use it was built for.
Intrusion detection and antivirus
Network intrusion detection systems such as Snort and Suricata match packet payloads against thousands of signatures in one pass, and offer Aho–Corasick-based matchers for it. Signature scanning in antivirus engines has the same shape.
Word filters and keyword tagging
Profanity filters, entity taggers and “highlight every term from this glossary” features scan text once against a fixed word list. The list changes rarely and the text arrives constantly, the case where building the automaton up front pays off.
Bioinformatics
Scanning a genome or a set of sequencing reads for a library of known short motifs or adapter sequences is a multi-pattern search over a very long text.
SOLVE IT YOURSELF
Solve it: search for every pattern at once
Running KMP once per pattern costs O(k·n). Aho–Corasick builds one automaton from all of them and finds every occurrence in a single pass over the text. Python or TypeScript.
YOUR TASK
Implement find_all(text, patterns): return every (index, pattern) occurrence, sorted. Overlapping matches all count — "aaa" against ["a","aa"] yields five.
HINTS — 6 IDEAS
First build a trie of all the patterns. Each node marks which patterns end there.
Then add failure links by BFS. A node’s failure link points at the longest proper suffix of its path that is also a node in the trie — exactly KMP’s idea, generalised to many patterns.
Crucially, merge the output sets along failure links: out[v] += out[fail[v]]. Without this, "hers" reports but the "he" inside it never does.
BFS order matters — fail[v] is always computed before any node deeper than v needs it.
To scan: for each character, follow failure links while there is no matching edge, then take the edge. Report everything in the node’s output set.
The whole scan is O(n + total pattern length + number of matches), regardless of how many patterns there are.