{"id":242,"date":"2026-11-13T12:35:40","date_gmt":"2026-11-13T04:35:40","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-rabin-karp-rolls-a-hash-across-the-text\/"},"modified":"2026-11-13T21:53:31","modified_gmt":"2026-11-13T13:53:31","slug":"how-rabin-karp-rolls-a-hash-across-the-text","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-rabin-karp-rolls-a-hash-across-the-text\/","title":{"rendered":"How Rabin-Karp rolls a hash across the text"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Rabin-Karp<\/strong> hashes the pattern and every window of the text. A polynomial rolling hash updates the next window in constant time: subtract the outgoing character, multiply by the radix, and add the incoming character, all modulo a prime. Equal hashes are candidates and must be verified character by character, because a collision is possible. Expected time is <strong>O(n + m)<\/strong> for one pattern with a random modulus. The worst case, under repeated collisions, is <strong>\u0398(nm)<\/strong>.<\/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\">KMP compares characters and guarantees a linear worst case. A hash compares windows as numbers. If the hash can be updated by the character that leaves and the character that enters, the scan does not rehash the window from scratch. The arithmetic is a polynomial in a radix, usually a prime number of characters or a power of two, evaluated modulo a large prime.<\/p>\n\n\n<p class=\"wp-block-paragraph\">A hit is not yet a match. Different strings can share a hash. Verification reads the window. The algorithm is exact only because of that read, and it is fast only when the false hits are rare.<\/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\">With a modulus that is prime and a radix coprime to it, one window update is O(1) arithmetic. Verification of a true match costs O(m), and a false collision costs O(m) as well. If the modulus is chosen so collisions are unlikely, one pattern is expected linear time. An adversary who knows the modulus can force collisions and the \u0398(nm) bound. Extra memory is a handful of integers for one pattern, or a set of pattern hashes for several patterns.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Multiple patterns are the setting where the method earns its keep: hash every pattern into a table, roll once across the text, and verify the few windows whose hash hits the table. Aho-Corasick is the deterministic automaton for that problem and does not collide. Rabin-Karp is simpler and randomized.<\/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>Choose a radix R and a large prime modulus M. Compute the pattern hash and the hash of the first window of the text, and compute R^{m\u22121} mod M for the outgoing-character term.<\/li>\n<li>If the hashes match, compare the window to the pattern character by character and report a real match.<\/li>\n<li>To slide one position, subtract the outgoing character times R^{m\u22121}, multiply the remainder by R, add the incoming character, and reduce modulo M. Keep the value nonnegative.<\/li>\n<li>Repeat the comparison test at each window.<\/li>\n<li>For several patterns, insert every pattern hash into a dictionary and verify every window that hits, against the patterns that share that hash.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The expected linear bound is not a worst-case bound. KMP and the Z-algorithm are deterministic linear searches. Rabin-Karp is the rolling-hash search, and it is also the subroutine inside some randomized string algorithms that really do want the hash rather than the match positions. A double hash with two moduli makes an adversarial collision harder and does not turn the worst case into a theorem.<\/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 a hash hit is reported as a match<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Skip the character comparison<\/td>\n<td>A collision prints a false occurrence. The hash is a filter.<\/td>\n<\/tr>\n<tr>\n<td>Recompute the window hash from scratch at every index<\/td>\n<td>The result is correct and the time is \u0398(nm) arithmetic. The rolling update is the algorithm.<\/td>\n<\/tr>\n<tr>\n<td>Reduce modulo a power of two with a small radix and no verification plan<\/td>\n<td>Structured collisions become easy. Verification still saves correctness, and the expected-time story gets worse.<\/td>\n<\/tr>\n<tr>\n<td>Quote O(n + m) worst case<\/td>\n<td>That bound belongs to KMP. Rabin-Karp&#8217;s worst case is quadratic when every window collides.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Deterministic linear search belongs to KMP or the Z-algorithm. Many patterns in worst-case linear time belong to Aho-Corasick. Rabin-Karp is the rolling-hash filter, strongest when several patterns share one scan and collisions are verified.<\/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 rolls a hash across the text and checks every hash hit against the pattern. It prints the verified index <code>2<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def rabin(text, pat, base=257, mod=1_000_000_007):\n    n, m = len(text), len(pat)\n    if m &gt; n:\n        return -1\n    high = pow(base, m - 1, mod)\n    hp = ht = 0\n    for i in range(m):\n        hp = (hp * base + ord(pat[i])) % mod\n        ht = (ht * base + ord(text[i])) % mod\n    for i in range(n - m + 1):\n        if ht == hp and text[i:i + m] == pat:\n            return i\n        if i + m &lt; n:\n            ht = (ht - ord(text[i]) * high) % mod\n            ht = (ht * base + ord(text[i + m])) % mod\n    return -1\n\nassert rabin(&quot;hello&quot;, &quot;ll&quot;) == 2\nprint(rabin(&quot;hello&quot;, &quot;ll&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 rolling hash of Rabin-Karp is the same idea as the weak rolling checksum in <strong>rsync<\/strong>: slide a window, update the hash in constant time, and confirm a hit with a stronger check. Plagiarism scanners hash document windows the same way. An exact automaton does not roll a hash.<\/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 Rabin-Karp when a worst-case linear guarantee is required. Use KMP. Keep it for multi-pattern filtering, for teaching the rolling hash, and anywhere a later algorithm already assumes a polynomial hash of windows.<\/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 Rabin-Karp returns the rolling update and the verification that a hash collision still requires. <strong>Rabin-Karp rolls a polynomial hash across each window in constant time and verifies every hit, which is expected linear time and worst-case quadratic time.<\/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: Rabin-Karp hashes the pattern and every window of the text. A polynomial rolling hash updates the next window in constant time: subtract the outgoing character, multiply by the radix, and add the incoming character, all modulo a prime. Equal hashes are candidates and must be verified character&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-242","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\/242","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=242"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/242\/revisions"}],"predecessor-version":[{"id":641,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/242\/revisions\/641"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=242"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=242"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=242"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}