V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Aho-Corasick Automaton

Build a trie of patterns, add failure links by BFS, and report overlapping matches during one text scan.

Core idea

Store all patterns in one trie. Failure links connect each state to its longest suffix that is also a trie prefix, so a mismatch reuses text already read instead of restarting every pattern.

Read the visualization

Solid edges form the trie and dashed edges show failures. The active automaton state follows each text character, and output links report overlapping pattern endings.

εhehe

Insert the next pattern through shared trie-prefix edges.

1function ahoCorasick(patterns: string[], text: string): [number, number][] {
2 const next: Record<string, number>[] = [{}]; // state 0 = root
3 const out: number[][] = [[]]; const fail = [0];
4 for (let pi = 0; pi < patterns.length; pi++) { // insert Trie: insert pattern insert
5 let s = 0;
6 for (const c of patterns[pi]) {
7 if (next[s][c] === undefined) { next.push({}); out.push([]); fail.push(0); next[s][c] = next.length - 1; }
8 s = next[s][c];
9 }
10 out[s].push(pi); // pattern insert point
11 }
12 const q: number[] = [];
13 for (const c in next[0]) q.push(next[0][c]); // BFS start point: root fail child fail=root
14 while (q.length) {
15 const u = q.shift()!;
16 for (const c in next[u]) { // BFS fail fail
17 const v = next[u][c]; q.push(v);
18 let f = fail[u];
19 while (f && next[f][c] === undefined) f = fail[f]; // fail parent fail fail fail c fail
20 fail[v] = next[f][c] !== undefined && next[f][c] !== v ? next[f][c]: 0;
21 out[v] = out[v].concat(out[fail[v]]); // output fail merge
22 }
23 }
24 const hits: [number, number][] = []; let s = 0;
25 for (let i = 0; i < text.length; i++) {
26 while (s && next[s][text[i]] === undefined) s = fail[s]; // match fail match
27 s = next[s][text[i]] ?? 0;
28 for (const pi of out[s]) hits.push([pi, i]); // hit hit (hit output hit duplicate hit)
29 }
30 return hits;
31}
pattern set{he, she, hers}
textushers
built state3 / 8
1 / 17

Complexity and tradeoffs

Time: O(P+n+z). Space: O(P × alphabet) dense. P is total pattern length and z is output count; sparse transitions reduce memory.

Invariant: After consuming text position i, the active state represents the longest suffix of the processed text that is also a pattern prefix.

Where it fits

Aho-Corasick powers dictionary scanning, moderation filters, intrusion signatures, and lexing when many patterns must be found in the same stream.