How Rabin-Karp rolls a hash across the text

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 by character, because a collision is possible. Expected time is O(n + m) for one pattern with a random modulus. The worst case, under repeated collisions, is Θ(nm).


What the problem actually asks

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.

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.


What the algorithm guarantees

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 Θ(nm) bound. Extra memory is a handful of integers for one pattern, or a set of pattern hashes for several patterns.

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.


The working steps

  1. 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−1} mod M for the outgoing-character term.
  2. If the hashes match, compare the window to the pattern character by character and report a real match.
  3. To slide one position, subtract the outgoing character times R^{m−1}, multiply the remainder by R, add the incoming character, and reduce modulo M. Keep the value nonnegative.
  4. Repeat the comparison test at each window.
  5. For several patterns, insert every pattern hash into a dictionary and verify every window that hits, against the patterns that share that hash.

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.


Approaches that look simpler and fail

Approach Why it fails when a hash hit is reported as a match
Skip the character comparison A collision prints a false occurrence. The hash is a filter.
Recompute the window hash from scratch at every index The result is correct and the time is Θ(nm) arithmetic. The rolling update is the algorithm.
Reduce modulo a power of two with a small radix and no verification plan Structured collisions become easy. Verification still saves correctness, and the expected-time story gets worse.
Quote O(n + m) worst case That bound belongs to KMP. Rabin-Karp’s worst case is quadratic when every window collides.

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.


A working example

This Python fragment rolls a hash across the text and checks every hash hit against the pattern. It prints the verified index 2.

def rabin(text, pat, base=257, mod=1_000_000_007):
    n, m = len(text), len(pat)
    if m > n:
        return -1
    high = pow(base, m - 1, mod)
    hp = ht = 0
    for i in range(m):
        hp = (hp * base + ord(pat[i])) % mod
        ht = (ht * base + ord(text[i])) % mod
    for i in range(n - m + 1):
        if ht == hp and text[i:i + m] == pat:
            return i
        if i + m < n:
            ht = (ht - ord(text[i]) * high) % mod
            ht = (ht * base + ord(text[i + m])) % mod
    return -1

assert rabin("hello", "ll") == 2
print(rabin("hello", "ll"))

Where it is used

The rolling hash of Rabin-Karp is the same idea as the weak rolling checksum in rsync: 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.


When you can drop this algorithm

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.


Why this stays published

We publish this so a search for Rabin-Karp returns the rolling update and the verification that a hash collision still requires. 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.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *