Algorithms · Visualized

String: Aho-Corasick

String Matching

Find a pattern inside a text efficiently — from the naive slide to prefix-function smartness.

Aho-Corasick finds ALL of many patterns in a single pass over the text. Time: O(n + m) average, O(n + matches) worst; space: O(sum of pattern lengths × alphabet size).

Big-O: Naive O(n·m); KMP & Z O(n+m); Rabin–Karp O(n+m) average with hashing.

Aho-Corasick

String Matching

Aho-Corasick finds ALL of many patterns in a single pass over the text. It builds a trie containing every pattern and augments it with failure links (KMP's failure function generalized to a trie): on a mismatch the automaton jumps to the longest proper suffix of the current path that is also a trie prefix, so no text character is ever re-read.

How Aho-Corasick Works

  1. Insert every pattern into a trie, merging shared prefixes (e.g. 'he' and 'hers' share 'h-e').
  2. Run BFS over the trie: each node's failure link points to the state of its longest proper suffix that exists in the trie.
  3. Propagate output links so a match that ends at an ancestor state is also reported at the current state.
  4. Scan the text once: follow trie edges for matching characters, failure links on mismatches.
  5. Whenever the current state has outputs, report every pattern match ending at the current text position.

Aho-Corasick Worked Example

Input: {text: ushers, patterns: [he, she, his, hers]}

Build the trie of all 4 patterns ('he' and 'hers' share the 'he' prefix). BFS assigns failure links, e.g. state 'she' links to 'he'. Scan u-s-h: no edge from root for 'u','s','h'... 'h' enters the trie. Then e: 'he' matched → report 'he'@2. Continuing, output links catch 'she'@1 (via the failure link) and when 'r','s' arrive they report 'hers'@2 — all in one linear pass.

String: Aho-CorasickO(n + m)
Build a trie of many patterns with failure links (KMP generalized) and scan once.
statecharfailoutputs
u
s
h
e
r
s
012345
state0
Step 1 / 36
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Aho-Corasick: build a trie of all 4 patterns — shared prefixes merge.
Python · String Matching in Code
def kmp_search(text, pat):
    lps = [0] * len(pat)
    j = 0
    for i in range(1, len(pat)):
        while j > 0 and pat[i] != pat[j]:
            j = lps[j - 1]
        if pat[i] == pat[j]:
            j += 1
        lps[i] = j
    out = []
    j = 0
    for i, c in enumerate(text):
        while j > 0 and c != pat[j]:
            j = lps[j - 1]
        if c == pat[j]:
            j += 1
        if j == len(pat):
            out.append(i - j + 1)
            j = lps[j - 1]
    return out

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Aho-Corasick Time & Space Complexity

BestO(n + m)
AverageO(n + m)
WorstO(n + matches)
SpaceO(sum of pattern lengths × alphabet size)

When to Use Aho-Corasick

  • Antivirus / intrusion-detection multi-signature scanning.
  • Search-and-highlight of many keywords at once (spam and profanity filters).
  • Bioinformatics multi-motif search.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.