Skip to content
Multiple

Aho-Corasick Algorithm

Multiple pattern matching using an automaton.

Time Complexity
O(N + M + K)
Space Complexity
O(M)

Interactive Visualization

Multi-Pattern DFA
root
a
sh
h
e
Failure Link

Built from words: ["ash", "she"]. Linear time O(N + total_patterns_len).

Technical Guide

Aho-Corasick is the gold standard for multi-pattern matching. It builds a finite automaton (a Trie with failure links) from a set of patterns. It can find all occurrences of all patterns in a text in one single pass. It is the core algorithm used in tools like `fgrep` and virus scanners.

Logical Phases

  • 1
    Building a Trie of all target patterns.
  • 2
    Adding 'Failure Links' that point to the longest proper suffix that is also a prefix in the tree.
  • 3
    Traversing the text through the automaton states.
  • 4
    Emitting matches whenever an 'output' state is reached.

Implementation

while (!curr.next[char]) curr = curr.fail;

Expert Pitfalls

Memory consumption grows with the total size of the pattern dictionary.