Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(n+m+z)O(n + m + z), 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 O(m)O(m) total time, by a telescoping argument on depths.
  • Prove that a scan reports all zz occurrences in O(n+z)O(n + z) time, and count the occurrences of every pattern in O(n+m)O(n + m) 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 P1,…,PkP_1, \dots, P_k of total length mm and a text tt of length nn, report every pair (position, pattern) at which a pattern occurs, and let zz be their number. Running KMP once per pattern costs O(m+kn)O(m + kn); restarting a walk down the trie at every text position costs O(m+nLmax⁡)O(m + n L_{\max}) for the longest pattern length Lmax⁡L_{\max}. The Aho–Corasick automaton reads each text character once, in amortized O(1)O(1) time, plus O(1)O(1) per occurrence reported.

Proof. TT is closed under prefixes, so the suffixes of str(v)\mathrm{str}(v) that lie in TT are, from longest to shortest, exactly v,fail(v),fail2(v),…v, \mathrm{fail}(v), \mathrm{fail}^2(v), \dots, ending at the root: each link jumps to the longest one that is shorter. A suffix of t[0..i]t[0..i] in TT has the form ucuc, where uu is a suffix of t[0..i−1]t[0..i-1] in TT with a child labeled cc; by induction those uu form the failure chain of the previous state, and the scan tries them from the longest. Finally, every pattern ending at ii is a suffix of t[0..i]t[0..i] in TT, so it is a node of the current state's failure chain, and the output links visit exactly the pattern nodes of that chain.

NodefailoutEnds a pattern?
h, s, hi, herrootnoneno
herootnoneyes
shhnoneno
hissnoneyes
sheheheyes
herssnoneyes
The automaton for the keywords of Aho and Corasick's paper, he, she, his and hers: nine nodes besides the root. Reading "she" also completes "he", which the output link of "she" reports.
Predict before you look

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 v=g(u,c)v = g(u, c) with u≠u \ne root, then fail(v)=g(f,c)\mathrm{fail}(v) = g(f, c) for the first node ff on the chain fail(u),fail2(u),…\mathrm{fail}(u), \mathrm{fail}^2(u), \dots, root that has a child labeled cc, or the root if none has. This is the scanning invariant applied to str(u)\mathrm{str}(u) followed by cc, 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: out(v)=fail(v)\mathrm{out}(v) = \mathrm{fail}(v) if a pattern ends at fail(v)\mathrm{fail}(v), and out(fail(v))\mathrm{out}(\mathrm{fail}(v)) otherwise.

python
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, order

Node 0 is the root and −1-1 means "none". The list order (breadth-first order) is kept for counting occurrences later.

DerivationTheorem: all failure links take O(m) time
  1. φ(v)  ≤  φ(parent(v))+1−s(v)\varphi(v) \;\le\; \varphi(\mathrm{parent}(v)) + 1 - s(v)

    Let φ(v)\varphi(v) be the depth of fail(v)\mathrm{fail}(v), and s(v)s(v) the number of chain steps taken while computing it. The walk starts at fail(parent(v))\mathrm{fail}(\mathrm{parent}(v)), every step strictly lowers the depth, and the final goto step adds 1:

  2. ∑j=1∣P∣s(vj)  ≤  ∣P∣−1+φ(v1)−φ(v∣P∣)  ≤  ∣P∣\sum_{j=1}^{\abs{P}} s(v_j) \;\le\; \abs{P} - 1 + \varphi(v_1) - \varphi(v_{\abs{P}}) \;\le\; \abs{P}

    Sum along the path v1,…,v∣P∣v_1, \dots, v_{\abs{P}} of one pattern PP, with φ(v1)=0\varphi(v_1) = 0 and s(v1)=0s(v_1) = 0 at depth 1. The sum telescopes, and depths are nonnegative:

  3. ∑vs(v)  ≤  ∑i=1k ∑v∈path(Pi)s(v)  ≤  ∑i=1k∣Pi∣=m\sum_{v} s(v) \;\le\; \sum_{i=1}^{k}\ \sum_{v \in \mathrm{path}(P_i)} s(v) \;\le\; \sum_{i=1}^{k} \abs{P_i} = m

    Every node lies on the path of at least one pattern, so summing over all patterns counts every node's steps at least once:

  4. Tbuild=O(m)T_{\text{build}} = O(m)

    With O(1)O(1) 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 log⁡∣Σ∣\log \abs{\Sigma}.

Scanning in O(n + z), and counting without listing

python
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 hits

scan("ushers", ["he", "she", "his", "hers"]) returns [(1, 'she'), (2, 'he'), (2, 'hers')].

DerivationTheorem: the scan takes O(n + z) time
  1. di  ≤  di−1+1−fid_i \;\le\; d_{i-1} + 1 - f_i

    Let did_i be the depth of the state after ii characters, d0=0d_0 = 0, and fif_i the number of failure links followed while reading character ii. Each link lowers the depth by at least 1 and the goto step raises it by at most 1:

  2. ∑i=1nfi  ≤  n+d0−dn  ≤  n\sum_{i=1}^{n} f_i \;\le\; n + d_0 - d_n \;\le\; n

    Summing over the whole text, the depths telescope, and dn≥0d_n \ge 0:

  3. Tscan=O(n+∑ifi+∑i(1+zi))=O(n+z)T_{\text{scan}} = O\Big(n + \sum_i f_i + \sum_i (1 + z_i)\Big) = O(n + z)

    Reporting: every node visited on the output chain at position ii ends a different pattern, so the walk costs O(1+zi)O(1 + z_i), where ziz_i counts the occurrences ending at ii. In total:

  4. Ω(n+m+z) is necessary\Omega(n + m + z)\ \text{is necessary}

    Any algorithm must read the input and write its output, so with the O(m)O(m) construction, Aho–Corasick's O(n+m+z)O(n + m + z) is optimal for a constant alphabet.

Often only the number of occurrences of each pattern is needed, and then zz 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 PjP_j ends at position ii exactly when the state after reading t[0..i]t[0..i] lies in the subtree of PjP_j'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.

python
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.

Check your understanding

You need the number of occurrences of each of 10510^5 patterns (total length 10610^6) in a text of 10610^6 characters, and the total number of occurrences can exceed 101010^{10}. What do you do?

  1. Scan with output links and count each reported occurrence
  2. Run KMP once for each pattern
  3. Record the state after each character, then sum the counts up the failure tree
  4. 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 O(n+m)O(n + m), about 2×1062 \times 10^6 steps, however many occurrences there are. Reporting occurrences one by one costs O(n+m+z)O(n + m + z) with z>1010z > 10^{10}.

From KMP to Hyperscan: practice and the frontier

With one pattern pp, the trie is a path and fail(p[0..i])\mathrm{fail}(p[0..i]) is the node of pp's longest proper border, of length π[i]\pi[i], KMP's prefix function. For p=p = abababca, the failure depths along the path are 0, 0, 1, 2, 3, 4, 0, 1, exactly π\pi. 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.

MethodPreprocessingScanNotes
KMP once per patternO(m)O(m)O(kn)O(kn)fine for a handful of patterns
trie walked from each positionO(m)O(m)O(nLmax⁡+z)O(n L_{\max} + z)no failure links
Aho–CorasickO(m)O(m)O(n+z)O(n + z)optimal for a constant alphabet
Aho–Corasick, full DFAO(m∣Σ∣)O(m \abs{\Sigma})exactly nn transitions +O(z)+ O(z)small alphabets
Commentz-Walter (1979)O(m)O(m)O(nLmax⁡)O(n L_{\max}) worst caseBoyer–Moore-style shifts over a trie of reversed patterns; can skip text when patterns are long
Wu–Manber (1994)O(m)O(m) plus tablesno linear worst-case boundhashes blocks of characters to shift; fast on large sets of long patterns
Skipping algorithms can read fewer than nn characters on typical inputs, which a one-pass automaton never does; Aho–Corasick wins on worst-case guarantees and on short 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 t[0..i]t[0..i], the state is the longest suffix of t[0..i]t[0..i] in the trie, and the patterns ending at ii are the state and its output chain.
  • Breadth-first construction takes O(m)O(m) and a scan O(n+z)O(n + z), 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 O(m∣Σ∣)O(m \abs{\Sigma}) space.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the automaton for he, she, his and hers, where does the failure link of the node "hers" point?

  1. The root
  2. "he"
  3. "s"
  4. "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.

Question 2

Why does scanning a text of length nn follow at most nn failure links in total, even though one character can trigger many?

  1. Each pattern can trigger at most one failure link per occurrence
  2. 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
  3. Failure links always point to the root, so each character follows at most one
  4. 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: nn characters add at most nn 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 nn, an amortized O(1)O(1) per character.

Question 3

With a single pattern pp, the Aho–Corasick trie is a path. Where does the failure link of the node for p[0..i]p[0..i] point?

  1. To the node for p[0..i−1]p[0..i-1], one step up
  2. Always to the root
  3. To the node for p[0..π[i]−1]p[0..\pi[i]-1], where π\pi is KMP's prefix function
  4. To the node for the longest suffix of p[0..i]p[0..i], including p[0..i]p[0..i] itself
Show the answer

C. To the node for p[0..π[i]−1]p[0..\pi[i]-1], where π\pi is KMP's prefix function

The longest proper suffix of p[0..i]p[0..i] that is a prefix of pp is its longest border, of length π[i]\pi[i]. So Aho–Corasick with one pattern is exactly KMP, and its failure links are the prefix function.

Question 4

You match 2,000 DNA motifs (alphabet A, C, G, T) of total length 5×1045 \times 10^4 against a genome of 3×1093 \times 10^9 bases. Which variant fits best?

  1. The full automaton, with δ(v,c)\delta(v, c) precomputed for all four characters
  2. KMP run once per motif
  3. A trie walked from every genome position
  4. The automaton with hash-map children and failure loops
Show the answer

A. The full automaton, with δ(v,c)\delta(v, c) precomputed for all four characters

With ∣Σ∣=4\abs{\Sigma} = 4 the table has about 4×5×104=2×1054 \times 5 \times 10^4 = 2 \times 10^5 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.