Skip to the workspace
Pebellslearn by building
String Algorithms  ›  Lesson

Aho-Corasick: Matching Many Patterns at Once

Aho-Corasick 30 minA trie of patterns with failure links, so one text pass finds every pattern

dsa / Aho-Corasick: Matching Many Patterns at Once

Explore each scene at your own pace.

01 · Scanning a document for every banned word at once

Scanning a document for every banned word at once

Aho-Corasick: Matching Many Patterns at Once

Definition
The Aho-Corasick algorithm finds every occurrence of every pattern from a dictionary in a single pass over the text. It builds a trie of the patterns and adds failure links that say where to continue when a match breaks, as KMP does with borders.
In plain words
It is a word filter that reads a post once instead of once per banned word. All the banned words are merged into one tree, and when a match breaks it jumps to the next best place in the tree instead of starting over.

In short: KMP finds one pattern in one text pass. Aho-Corasick finds every pattern in a whole dictionary in one text pass. Build a trie (section 4's structure) of all the patterns, then give every node a failure link — "if matching breaks here, where in the trie should I carry on from?" — the same idea as KMP's border, generalised from one string to a whole tree of them. The text pointer still never moves backwards; only the trie pointer jumps.

A trie of the words he, she, his and hers, with a dashed failure-link arrow from the deep node reached by 's','h' pointing back up to the node reached by 'h' alone

Scanning a document for every banned word at once

A moderation filter checks a post against a list of a thousand banned phrases. Calling .find() once per phrase means reading the post a thousand times — O(n · k) for k phrases. A trie merges the phrases that share a prefix, so the text is only ever read once, no matter how many phrases there are.

python

This gives the right answer, but it scans "ushers" four separate times. Aho-Corasick reads it once and finds all four matches (or, here, the three that actually occur) as it goes.

Scene 1 of 7
Project context and further resources
You're building a piece ofQuarry — the text index
This piece — kmp_search(): Finds every occurrence in one forward pass, never re-reading the text.
Scenario Quarry's text index needs to flag every one of a few thousand tracked phrases inside a new document without rereading the document once per phrase.
find_all_patterns.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
find_all_patterns(text, patterns) → dictEvery starting index where each pattern occurs in text.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.