7. Aho-Corasick

Search for many patterns at once with a trie automaton

Suppose you have a text of n characters and a dictionary of k patterns with total length m. You need to find every occurrence of every pattern in the text. The naive approach — run KMP once per pattern — takes O(n × k + m) time. If you have thousands of patterns, that's thousands of passes over the text.

In 1975, Alfred Aho and Margaret Corasick published an algorithm that solves this problem in a single pass. Their key insight: merge all the patterns into one automaton, then scan the text exactly once. The algorithm powers everything from intrusion detection systems to antivirus scanners — anywhere you need to match many patterns simultaneously.

The Problem: Multi-Pattern Search

Single-pattern algorithms like KMP are elegant, but they fundamentally scan for one pattern at a time. If you have k patterns, you make k passes:

Why per-pattern search is wasteful

Text:     "ushers"
Patterns: {"he", "she", "his", "hers"}

Pass 1 (KMP for "he"): scan all 6 chars → found at position 2 Pass 2 (KMP for "she"): scan all 6 chars → found at position 1 Pass 3 (KMP for "his"): scan all 6 chars → not found Pass 4 (KMP for "hers"): scan all 6 chars → found at position 2

Total: 4 × 6 = 24 character comparisons

With Aho-Corasick, we scan the 6 characters once and find all three matches.

Step 1: Build a Trie

A trie (prefix tree) stores all patterns in a shared tree structure where common prefixes are merged. Each edge is labeled with a character, and each path from root to a node spells out a prefix of some pattern.

Trie for {"he", "she", "his", "hers"}

         (root)
        /      \
       h        s
      / \        \
     e   i        h
     |   |         \
     r   s          e
     |
     s

Nodes marked as pattern-end: he, his, hers, she

Path root→h→e = "he" ✓ Path root→h→e→r→s = "hers" ✓ Path root→h→i→s = "his" ✓ Path root→s→h→e = "she" ✓

Building the trie is straightforward: for each pattern, walk from the root, creating new nodes as needed. Mark the final node of each pattern as an output node.

Pseudocode: Trie Construction

function buildTrie(patterns):
    root = new TrieNode()

    for each pattern in patterns:
        node = root
        for each char c in pattern:
            if node.children[c] does not exist:
                node.children[c] = new TrieNode()
            node = node.children[c]
        node.output.add(pattern)    // mark as end of pattern

    return root

Step 2: Add Failure Links

Here's where Aho-Corasick becomes clever. A failure link from a node points to the longest proper suffix of the string spelled by that node that is also a prefix of some pattern in the trie. This is exactly the same idea as KMP's failure function, but generalized to a trie.

The Failure Link Rule

If you're at a node that spells the string w, the failure link points to the node spelling the longest proper suffix of w that exists in the trie. If no such suffix exists, the failure link points to the root.

When the automaton can't follow a character from the current node, it follows the failure link — just like KMP avoids re-scanning characters it has already matched.

  1. Root and depth-1 nodes

    The root's failure link points to itself. All depth-1 nodes (single-character prefixes) have failure links to the root, because the only proper suffix of a single character is the empty string.

  2. BFS to build the rest

    Process nodes in breadth-first order. For each node u reached by character c from parent p: follow p's failure link to f. If f has a child on c, that child is u's failure link. Otherwise, follow f's own failure link and repeat. If you reach the root with no match, the failure link is the root.

  3. Worked example

    In our trie, consider the node at path s→h→e (spelling "she"). The proper suffixes of "she" are "he" and "e". The string "he" does exist in the trie (path h→e), so the failure link from the "she" node points to the "he" node.

Failure links for {"he", "she", "his", "hers"}

Node (string)    Failure link → (string)
─────────────    ──────────────────────
root             → root
h                → root
s                → root
h→e              → root       (no suffix of "he" in trie besides "")
h→i              → root
s→h              → h          ("h" is a suffix of "sh" and exists in trie)
h→e→r            → root
h→i→s            → s          ("s" is a suffix of "his" and exists in trie)
s→h→e            → h→e        ("he" is a suffix of "she" and exists!)
h→e→r→s          → s          ("s" is a suffix of "hers" and exists)

Pseudocode: Failure Link Construction (BFS)

function buildFailureLinks(root):
    queue = new Queue()

    // Depth-1 nodes: failure → root
    for each child c of root:
        c.fail = root
        queue.enqueue(c)

    // BFS
    while queue is not empty:
        current = queue.dequeue()

        for each (char, child) in current.children:
            // Walk up failure links to find the longest suffix
            fallback = current.fail
            while fallback ≠ root and char not in fallback.children:
                fallback = fallback.fail

            child.fail = fallback.children[char] if char in fallback.children
                         else root
            // Don't point to yourself
            if child.fail == child:
                child.fail = root

            queue.enqueue(child)

Step 3: Add Dictionary Links

There's one subtlety left. When you reach a node via a failure link, that node might itself be a pattern endpoint. And its failure link might lead to yet another pattern endpoint. A dictionary link (also called an output link) short-circuits directly to the next pattern-ending node reachable by following failure links.

Why dictionary links matter

Consider the node for "she" (path s→h→e).
Its failure link points to the "he" node.
The "he" node IS a pattern endpoint.

So when we match "she", we must also report "he"!

Dictionary link for s→h→e → h→e (because h→e has output "he")

Without dictionary links, we'd miss overlapping pattern matches.

function buildDictionaryLinks(root):
    // During BFS (can be combined with failure link construction):
    for each node processed in BFS order:
        if node.fail has output:
            node.dictLink = node.fail
        else:
            node.dictLink = node.fail.dictLink  // may be null

The Search: Walking the Automaton

With the automaton fully constructed (trie + failure links + dictionary links), searching is beautifully simple:

  1. Start at the root

    Set the current state to the root node.

  2. For each character in the text

    Try to follow the edge for that character. If no edge exists, follow the failure link and try again. Repeat until you either find an edge or reach the root.

  3. Collect outputs

    At the new state, check if it's a pattern endpoint. Then follow dictionary links to collect any additional pattern matches (patterns that are suffixes of the current match).

Pseudocode: Search

function search(root, text):
    current = root
    results = []

    for i from 0 to length(text) - 1:
        char = text[i]

        // Follow failure links until we can advance
        while current ≠ root and char not in current.children:
            current = current.fail

        if char in current.children:
            current = current.children[char]

        // Collect all pattern matches at this state
        temp = current
        while temp ≠ root:
            if temp.output is not empty:
                for each pattern in temp.output:
                    results.add((i - length(pattern) + 1, pattern))
            temp = temp.dictLink or break

    return results

Full Worked Example: Searching "ushers"

Patterns: {"he", "she", "his", "hers"} — Text: "ushers"

Position  Char  State (path)      Action                    Matches found
────────  ────  ─────────────      ──────                    ─────────────
   0       u    root               no 'u' child → stay       —
   1       s    s                  follow s edge             —
   2       h    s→h                follow h edge             —
   3       e    s→h→e              follow e edge             "she" at pos 1
                                   dict link → h→e           "he" at pos 2
   4       r    h→e→r              fail to h→e, follow r     —
                                   (s→h→e fails on 'r',
                                    fail→h→e has 'r' child)
   5       s    h→e→r→s            follow s edge             "hers" at pos 2

Results: "she" at 1, "he" at 2, "hers" at 2 Total: 6 characters scanned, 3 matches found

Let's trace the trickiest transition in detail — position 4 (character 'r'):

Detailed trace at position 4

Current state: s→h→e (just matched "she")
Next character: 'r'

  1. Does s→h→e have a child on 'r'? NO
  2. Follow failure link: s→h→e.fail = h→e
  3. Does h→e have a child on 'r'? YES → move to h→e→r
  4. Current state is now h→e→r (spelling "her")
  5. h→e→r has no output, no dict link → no match reported

The failure link let us "reuse" the fact that the end of "she" overlaps with the beginning of "hers" — we never re-scanned the 'h' or 'e'.

Complexity Analysis

Time Complexity: O(n + m + z)

Where n = length of text, m = total length of all patterns, and z = number of matches reported.

  • O(m) to build the trie — each pattern character creates at most one node
  • O(m) to compute failure links — the BFS visits each node once, and the total number of failure link hops is bounded by m (amortized argument similar to KMP)
  • O(n) to scan the text — each character advances or follows a failure link, and the total number of failure link hops across the entire scan is bounded by n
  • O(z) to report matches — each match is reported in constant time via dictionary links

Space: O(m × |Σ|) where |Σ| is the alphabet size, for the trie nodes and their child pointers. Using hash maps for children reduces this to O(m).

Comparison with alternatives

ApproachTimePasses over text
Naive (strstr per pattern) O(n × m) k passes
KMP per pattern O(n × k + m) k passes
Aho-Corasick O(n + m + z) 1 pass

The key insight is that Aho-Corasick's time does not depend on the number of patterns k — only on their total length m. Whether you have 10 patterns or 10,000, the text is scanned exactly once.

Where Aho-Corasick Is Used

Application How it uses Aho-Corasick
Intrusion detection (Snort) Scans network packets against thousands of known attack signatures simultaneously
Antivirus scanners Checks files against a database of malware byte-sequences in a single pass
DNA motif search Finds all occurrences of known regulatory sequences in a genome
Scrabble solvers Checks whether candidate words exist in the dictionary while exploring the board
Content filtering Detects banned words or phrases in text streams in real time
Bibliographic search The original 1975 paper was motivated by searching library catalogue entries

Key Takeaways

  • Aho-Corasick merges all patterns into a single trie automaton, enabling multi-pattern search in one pass over the text
  • Failure links generalize KMP's failure function to a trie — they let the automaton "fall back" to the longest matching suffix without re-scanning characters
  • Dictionary links ensure that overlapping pattern matches (like "she" containing "he") are never missed
  • The construction is O(m) and the search is O(n + z), making the total O(n + m + z) — optimal for multi-pattern matching
  • The algorithm's performance is independent of the number of patterns, depending only on their total length
  • It's the backbone of real-world systems that need to match thousands of patterns against streaming data: IDS, antivirus, DNA analysis

Aho-Corasick is one of those algorithms that feels almost magical — you build a single structure from all your patterns, and then a single linear scan finds every occurrence of every pattern. It's a perfect example of how preprocessing (building the trie and failure links) can make the actual search nearly effortless. The next time your antivirus scans a file in milliseconds against millions of signatures, you'll know there's a trie automaton doing the heavy lifting.