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 MatchingAho-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
- Insert every pattern into a trie, merging shared prefixes (e.g. 'he' and 'hers' share 'h-e').
- Run BFS over the trie: each node's failure link points to the state of its longest proper suffix that exists in the trie.
- Propagate output links so a match that ends at an ancestor state is also reported at the current state.
- Scan the text once: follow trie edges for matching characters, failure links on mismatches.
- 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.
| state | char | fail | outputs |
|---|
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 outBehind 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
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
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.