{"id":132,"date":"2026-11-13T12:32:16","date_gmt":"2026-11-13T04:32:16","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-aho-corasick-matches-many-patterns-at-once\/"},"modified":"2026-11-13T21:50:59","modified_gmt":"2026-11-13T13:50:59","slug":"how-aho-corasick-matches-many-patterns-at-once","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-aho-corasick-matches-many-patterns-at-once\/","title":{"rendered":"How Aho-Corasick matches many patterns at once"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Aho-Corasick<\/strong> builds a trie of every pattern and adds a failure link from each node to the longest proper suffix of its path that is still a node in the trie. A text character is consumed exactly once. On a missing edge the walk follows failure links, as KMP does on one string. Output links report every pattern that ends at the current node, including patterns that end at a suffix of the current path. The scan is <strong>O(n + m + z)<\/strong>, where m is the total pattern length and z is the number of matches.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Searching each pattern separately repeats the text. The trie represents all patterns at once. The missing piece is where to go when the next text character has no edge. The failure link answers that with the longest suffix that is a prefix of some pattern, which is the same border idea as KMP, lifted to a trie.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A node can complete more than one pattern, because a short pattern can be a suffix of a longer one&#8217;s path. Output links chain those completions so the scan does not walk the failure chain from scratch at every character.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Construction is O(m \u00b7 \u03c3) for an alphabet array, or O(m log \u03c3) with a map at each node. The text scan is O(n + z) after the automaton exists, with alphabet-array transitions. Extra memory is the trie. Every match is reported, including overlaps and patterns that end in the middle of another pattern&#8217;s match. The failure link of the root is the root, and the root has an edge for every character, possibly a self-loop, so the walk never gets stuck.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The algorithm is exact dictionary matching. It does not rank fuzzy hits. Adding a failure link that points at an arbitrary ancestor, rather than the longest proper suffix in the trie, misses matches or reads the same text character twice.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Insert every pattern into a trie and mark the node where that pattern ends.<\/li>\n<li>Breadth-first search from the root. The failure link of a depth-1 node is the root. For a deeper node reached by character c from parent p, follow p&#8217;s failure link until a node with a c edge appears, and point the new failure link at that edge&#8217;s target.<\/li>\n<li>Add the missing alphabet edges by cloning the failure link&#8217;s transition, so every node has a next state for every character. This is the automaton form.<\/li>\n<li>Set each node&#8217;s output link to the nearest failure-chain node that ends a pattern.<\/li>\n<li>Scan the text from the root, one character at a time, and at each node emit the patterns on its output chain.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear scan is for a fixed dictionary. Rebuilding the trie for every new pattern is a different cost. Approximate matching is bitap or an edit-distance automaton. A single pattern does not need output links. KMP is that special case. The breadth-first order of failure construction matters: a node&#8217;s failure target has to be computed before the node is processed, which BFS guarantees and a casual recursion may not.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the failure link skips the longest suffix<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Point every failure link at the root<\/td>\n<td>The transitions are correct only for patterns that never overlap a prefix. A suffix that is another pattern&#8217;s prefix is missed, and the scan can still be forced into quadratic backtracking if the links are followed naively.<\/td>\n<\/tr>\n<tr>\n<td>Emit only the pattern that ends at the current node<\/td>\n<td>A shorter pattern that is a suffix of the current path also matches. The output chain is what reports it.<\/td>\n<\/tr>\n<tr>\n<td>Build failure links in depth order that is not breadth-first<\/td>\n<td>A link may then point at a node whose own link is unfinished. The longest-suffix computation reads those links.<\/td>\n<\/tr>\n<tr>\n<td>Search the patterns one at a time and quote the Aho-Corasick bound<\/td>\n<td>r separate scans cost O(r \u00b7 n + m). The automaton pays for the text once.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">One pattern is KMP or Boyer-Moore. A rolling hash of many patterns is Rabin-Karp, with collisions to verify. Aho-Corasick is the deterministic multi-pattern automaton.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment builds the trie, then the failure links by breadth-first search, then the output links. Scanning <code>ushers<\/code> reports the patterns that end at each hit. It prints <code>she he hers<\/code>.<\/p>\n\n<pre><code class=\"language-python\">from collections import deque\npatterns = [&quot;he&quot;, &quot;she&quot;, &quot;his&quot;, &quot;hers&quot;]\ntrie = [{}]\nout = [[]]\nfail = [0]\n\ndef add(word, idx):\n    node = 0\n    for ch in word:\n        node = trie[node].setdefault(ch, len(trie))\n        if node == len(out):\n            trie.append({})\n            out.append([])\n            fail.append(0)\n    out[node].append(idx)\n\nfor i, word in enumerate(patterns):\n    add(word, i)\n\nqueue = deque()\nfor ch, nxt in trie[0].items():\n    queue.append(nxt)\nwhile queue:\n    u = queue.popleft()\n    for ch, v in trie[u].items():\n        queue.append(v)\n        f = fail[u]\n        while f and ch not in trie[f]:\n            f = fail[f]\n        fail[v] = trie[f][ch] if ch in trie[f] else 0\n        if fail[v] == v:\n            fail[v] = 0\n        out[v] = out[v] + out[fail[v]]\n\ntext = &quot;ushers&quot;\nnode = 0\nhits = []\nfor ch in text:\n    while node and ch not in trie[node]:\n        node = fail[node]\n    node = trie[node][ch] if ch in trie[node] else 0\n    for idx in out[node]:\n        hits.append(patterns[idx])\nassert hits == [&quot;she&quot;, &quot;he&quot;, &quot;hers&quot;]\nprint(*hits)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>ClamAV<\/strong> and <strong>ripgrep<\/strong> build an Aho-Corasick automaton so many literal patterns are matched in one pass over the text. Snort-style intrusion rules use the same machine. Searching for one pattern does not need the failure links.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop Aho-Corasick for a single short pattern, where Boyer-Moore or a library search is simpler. Keep it when a dictionary of patterns must be found in one left-to-right scan and every overlap has to be reported.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for Aho-Corasick returns the trie failure links and the output chain that reports a pattern ending in the middle of another. <strong>Aho-Corasick reports every occurrence of every pattern in one text scan by walking a trie whose failure links encode the longest suffix that is still a prefix.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Aho-Corasick builds a trie of every pattern and adds a failure link from each node to the longest proper suffix of its path that is still a node in the trie. A text character is consumed exactly once. On a missing edge the walk follows failure links,&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,38],"tags":[],"class_list":["post-132","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-strings"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/132","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=132"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/132\/revisions"}],"predecessor-version":[{"id":531,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/132\/revisions\/531"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=132"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=132"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=132"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}