Skip to content

ahoCorasick ​

Searches all patterns in one text and returns [endIndex, patternIndex] pairs. endIndex is the inclusive byte offset of the match; pairs are ordered by end offset and then pattern index.

tyrus
import { ahoCorasick } from "tyrus:algorithm";

const matches: [usize, usize][] = ahoCorasick("ababa", ["aba", "ba"]);
print(matches[0][0], matches[0][1]); // 2 0

Study result ​

tyrus
interface AhoCorasickInfo {
    text: string;
    patterns: string[];
    matches: [usize, usize][];
    visitedStates: usize[];
    transitionCount: usize;
    failureFollowCount: usize;
}
tyrus
import { AhoCorasickInfo, ahoCorasickInfo } from "tyrus:algorithm";

const info: AhoCorasickInfo = ahoCorasickInfo("ababa", ["aba", "ba"]);
print(info.text); // ababa
print(info.patterns); // [aba, ba]
print(info.matches); // [[2, 0], [2, 1], [4, 0], [4, 1]]
print(info.visitedStates); // [1, 2, 3, 2, 3]
print(info.transitionCount); // 5
print(info.failureFollowCount); // 2

The study result stores one automaton state per input byte. Its additional storage is O(n + p), where n is the text length and p is the total pattern length.

The automaton runs in O(text length + total pattern length + number of matches) time and uses O(total pattern length) auxiliary space.