How Aho-Corasick matches many patterns at once

Short answer: Aho-Corasick builds a trie of every pattern and adds a failure link from each node to the longest proper suffix of its path that is still a node in the trie. A text character is consumed exactly once. On a missing edge the walk follows failure links, as KMP does on one string. Output links report every pattern that ends at the current node, including patterns that end at a suffix of the current path. The scan is O(n + m + z), where m is the total pattern length and z is the number of matches.


What the problem actually asks

Searching each pattern separately repeats the text. The trie represents all patterns at once. The missing piece is where to go when the next text character has no edge. The failure link answers that with the longest suffix that is a prefix of some pattern, which is the same border idea as KMP, lifted to a trie.

A node can complete more than one pattern, because a short pattern can be a suffix of a longer one’s path. Output links chain those completions so the scan does not walk the failure chain from scratch at every character.


What the algorithm guarantees

Construction is O(m · σ) for an alphabet array, or O(m log σ) with a map at each node. The text scan is O(n + z) after the automaton exists, with alphabet-array transitions. Extra memory is the trie. Every match is reported, including overlaps and patterns that end in the middle of another pattern’s match. The failure link of the root is the root, and the root has an edge for every character, possibly a self-loop, so the walk never gets stuck.

The algorithm is exact dictionary matching. It does not rank fuzzy hits. Adding a failure link that points at an arbitrary ancestor, rather than the longest proper suffix in the trie, misses matches or reads the same text character twice.


The working steps

  1. Insert every pattern into a trie and mark the node where that pattern ends.
  2. Breadth-first search from the root. The failure link of a depth-1 node is the root. For a deeper node reached by character c from parent p, follow p’s failure link until a node with a c edge appears, and point the new failure link at that edge’s target.
  3. Add the missing alphabet edges by cloning the failure link’s transition, so every node has a next state for every character. This is the automaton form.
  4. Set each node’s output link to the nearest failure-chain node that ends a pattern.
  5. Scan the text from the root, one character at a time, and at each node emit the patterns on its output chain.

The linear scan is for a fixed dictionary. Rebuilding the trie for every new pattern is a different cost. Approximate matching is bitap or an edit-distance automaton. A single pattern does not need output links. KMP is that special case. The breadth-first order of failure construction matters: a node’s failure target has to be computed before the node is processed, which BFS guarantees and a casual recursion may not.


Approaches that look simpler and fail

Approach Why it fails when the failure link skips the longest suffix
Point every failure link at the root The transitions are correct only for patterns that never overlap a prefix. A suffix that is another pattern’s prefix is missed, and the scan can still be forced into quadratic backtracking if the links are followed naively.
Emit only the pattern that ends at the current node A shorter pattern that is a suffix of the current path also matches. The output chain is what reports it.
Build failure links in depth order that is not breadth-first A link may then point at a node whose own link is unfinished. The longest-suffix computation reads those links.
Search the patterns one at a time and quote the Aho-Corasick bound r separate scans cost O(r · n + m). The automaton pays for the text once.

One pattern is KMP or Boyer-Moore. A rolling hash of many patterns is Rabin-Karp, with collisions to verify. Aho-Corasick is the deterministic multi-pattern automaton.


A working example

This Python fragment builds the trie, then the failure links by breadth-first search, then the output links. Scanning ushers reports the patterns that end at each hit. It prints she he hers.

from collections import deque
patterns = ["he", "she", "his", "hers"]
trie = [{}]
out = [[]]
fail = [0]

def add(word, idx):
    node = 0
    for ch in word:
        node = trie[node].setdefault(ch, len(trie))
        if node == len(out):
            trie.append({})
            out.append([])
            fail.append(0)
    out[node].append(idx)

for i, word in enumerate(patterns):
    add(word, i)

queue = deque()
for ch, nxt in trie[0].items():
    queue.append(nxt)
while queue:
    u = queue.popleft()
    for ch, v in trie[u].items():
        queue.append(v)
        f = fail[u]
        while f and ch not in trie[f]:
            f = fail[f]
        fail[v] = trie[f][ch] if ch in trie[f] else 0
        if fail[v] == v:
            fail[v] = 0
        out[v] = out[v] + out[fail[v]]

text = "ushers"
node = 0
hits = []
for ch in text:
    while node and ch not in trie[node]:
        node = fail[node]
    node = trie[node][ch] if ch in trie[node] else 0
    for idx in out[node]:
        hits.append(patterns[idx])
assert hits == ["she", "he", "hers"]
print(*hits)

Where it is used

ClamAV and ripgrep build an Aho-Corasick automaton so many literal patterns are matched in one pass over the text. Snort-style intrusion rules use the same machine. Searching for one pattern does not need the failure links.


When you can drop this algorithm

Drop Aho-Corasick for a single short pattern, where Boyer-Moore or a library search is simpler. Keep it when a dictionary of patterns must be found in one left-to-right scan and every overlap has to be reported.


Why this stays published

We publish this so a search for Aho-Corasick returns the trie failure links and the output chain that reports a pattern ending in the middle of another. Aho-Corasick reports every occurrence of every pattern in one text scan by walking a trie whose failure links encode the longest suffix that is still a prefix.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *