{"id":208,"date":"2026-11-13T12:34:36","date_gmt":"2026-11-13T04:34:36","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-knuth-morris-pratt-skips-with-the-prefix-table\/"},"modified":"2026-11-13T21:52:49","modified_gmt":"2026-11-13T13:52:49","slug":"how-knuth-morris-pratt-skips-with-the-prefix-table","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-knuth-morris-pratt-skips-with-the-prefix-table\/","title":{"rendered":"How Knuth-Morris-Pratt skips with the prefix table"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> The <strong>Knuth-Morris-Pratt<\/strong> algorithm scans a text for a pattern in <strong>O(n + m)<\/strong> time. It builds a prefix table \u03c0, where \u03c0[i] is the longest proper prefix of the pattern that is also a suffix of the pattern ending at i. When a mismatch occurs after i matched characters, the next comparison resumes at \u03c0[i] instead of at the start of the pattern. The text index never moves backward.<\/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\">A naive scan shifts the pattern by one character after every mismatch and can reexamine a text character as many times as the pattern is long, which is \u0398(nm). The characters already matched are a string that is a prefix of the pattern. Any shift that still leaves a match must place a prefix of the pattern over a suffix of that matched string. The longest such prefix is exactly the information the next alignment needs, and it depends only on the pattern.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The prefix table is computed by the same automaton running on the pattern itself. It is not a scan of every substring.<\/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\">The table has length m and is built in O(m) comparisons. The scan of a text of length n performs O(n) comparisons, because the text index only increases and the pattern index increases at most n times and decreases in a way that is charged to those increases. Extra memory is the table. The algorithm reports every match, including overlaps. A match that ends at text position t starts at t \u2212 m.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The failure link is not the same object as the Z-box, although both are linear pattern automata. KMP&#8217;s link is a border length. The Z-algorithm&#8217;s value is the length of a prefix match starting at a position. Either one can search. KMP is the one that never rewinds the text.<\/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>Build \u03c0 for the pattern. Set \u03c0[0] = 0. For each later index i, start from the border length of i\u22121 and follow failure links until the next pattern character matches position i, or the length hits 0. Store that new border length.<\/li>\n<li>Set the pattern cursor q = 0. For each text character, follow \u03c0 while q &gt; 0 and the character does not match pattern[q], assigning q = \u03c0[q\u22121] with the usual 0-based adjustment.<\/li>\n<li>If the character matches, increment q. If q reaches m, report a match ending here and set q = \u03c0[m\u22121] so overlaps are still found.<\/li>\n<li>Do not decrement the text index.<\/li>\n<li>A missing match is the scan finishing with no time q reached m.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The linear bound is for a fixed pattern in a text, in the worst case, with no hashing. It does not filter approximate matches. A Boyer-Moore scan can skip characters in the text and has a worse worst case. Rabin-Karp hashes windows and must verify candidates. KMP is the deterministic linear scan that reuses borders.<\/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 pattern restarts at zero after every mismatch<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Shift the pattern by one and rescan<\/td>\n<td>That is the naive algorithm. Its worst case is \u0398(nm), which the prefix table exists to avoid.<\/td>\n<\/tr>\n<tr>\n<td>Set the next q to \u03c0[q] without the index adjustment the table was built with<\/td>\n<td>Off-by-one in the failure link skips a legal border or loops. The table&#8217;s definition and the lookup have to use the same indexing.<\/td>\n<\/tr>\n<tr>\n<td>Move the text index backward to the start of the last attempt<\/td>\n<td>The matched prefix already accounts for every text character just read. Rewinding reintroduces the quadratic comparisons.<\/td>\n<\/tr>\n<tr>\n<td>Use the table computed for a different pattern<\/td>\n<td>The borders are properties of the pattern. A new pattern needs a new table, still in O(m).<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A hash of each window is Rabin-Karp. A skip driven by the last mismatched text character is Boyer-Moore. A set of patterns, rather than one, is Aho-Corasick, which generalizes the same failure links to a trie.<\/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 KMP prefix table and never retreats the text index. It prints the starting indexes of <code>aba<\/code> inside <code>abacaba<\/code>, <code>0 4<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def prefix(pat):\n    pi = [0] * len(pat)\n    k = 0\n    for i in range(1, len(pat)):\n        while k and pat[k] != pat[i]:\n            k = pi[k - 1]\n        if pat[k] == pat[i]:\n            k += 1\n        pi[i] = k\n    return pi\n\ndef search(text, pat):\n    pi = prefix(pat)\n    hits, q = [], 0\n    for i, ch in enumerate(text):\n        while q and pat[q] != ch:\n            q = pi[q - 1]\n        if pat[q] == ch:\n            q += 1\n        if q == len(pat):\n            hits.append(i - len(pat) + 1)\n            q = pi[q - 1]\n    return hits\n\nassert search(&quot;abacaba&quot;, &quot;aba&quot;) == [0, 4]\nprint(*search(&quot;abacaba&quot;, &quot;aba&quot;))\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\">The Knuth-Morris-Pratt prefix table is the failure function of an exact scanner that preprocesses a pattern once and then streams a long text, such as a log or a DNA string. <strong>Boyer-Moore<\/strong> skips more on natural-language text. Many patterns at once are Aho-Corasick.<\/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 KMP when the practical text is long, the pattern is short, and a tuned Boyer-Moore or a library search already skips ahead. Keep KMP when the worst case must be linear, overlaps matter, and the text cursor must move only forward.<\/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 Knuth-Morris-Pratt returns the prefix table and the guarantee that the text index never retreats. <strong>Knuth-Morris-Pratt finds every occurrence of a pattern in O(n + m) time by resuming at the longest matched border, without moving the text index backward.<\/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: The Knuth-Morris-Pratt algorithm scans a text for a pattern in O(n + m) time. It builds a prefix table \u03c0, where \u03c0[i] is the longest proper prefix of the pattern that is also a suffix of the pattern ending at i. When a mismatch occurs after i&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-208","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\/208","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=208"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/208\/revisions"}],"predecessor-version":[{"id":607,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/208\/revisions\/607"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=208"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=208"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=208"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}