The Aho–Corasick algorithm
The Aho–Corasick algorithm finds several given strings in a single pass through the text. For example, it can find and highlight every term from a glossary in a document.
Video walkthrough
Previous episode: the prefix tree
From a trie to an automaton
Insert “she”, “he”, and “hers” in a trie. Traverse it breadth-first. For each node, find its longest proper suffix that is also a prefix in the trie. For “she” this is “he”. A failure link points to the root when no nonempty candidate exists.
What happens in “ushers”
After the fourth letter the state is “she”. That state reports “she”, and its output chain also reports “he”. The next letter is “r”. The state “she” has no “r” edge, so we follow the failure link to “he”. Now we can consume “r”, then “s”, to find “hers” at positions three through six.
Why one pass is enough
After consuming each character, the state represents the longest suffix of the text seen so far that is also a pattern prefix. A failure link shortens that prefix while preserving the part that may still lead to a match. After a successful transition, report every pattern ending at the current character.
Search cost
With amortized O(1) Map operations, scanning takes O(n + k), where n is the text length and k is the number of matches. A letter transition increases depth by one and a failure transition decreases it. Output links add constant work for each reported match. The automaton is built beforehand. The interactive separately stores snapshots for seeking.
Searching with a built automaton
nodes is an array of states with the root at index 0. children stores character transitions, fail is the state for the longest proper suffix, and outputLink points to the nearest pattern end on the failure chain or is null. length stores the pattern length. The function yields the pattern and inclusive zero-based Unicode code-point offsets.
function* findPatterns(nodes, text) {
let state = 0;
for (const [index, symbol] of Array.from(text).entries()) {
while (state && !nodes[state].children.has(symbol)) {
state = nodes[state].fail;
}
state = nodes[state].children.get(symbol) ?? 0;
for (let id = state; id !== null; id = nodes[id].outputLink) {
const word = nodes[id].word;
if (word) {
yield {
word,
from: index - nodes[id].length + 1,
to: index
};
}
}
}
}