TExcelTAD

Rabin-Karp and Rolling Hashes

The naive matcher compares mm characters to rule out a shift. Rabin and Karp (1987) replaced that with comparing one number: a hash of the text window against the hash of the pattern. The trick that makes it fast is the rolling hash: the hash of the next window is computed from the previous one in constant time. Equal hashes do not prove a match, so the algorithm still checks the characters on a hit, but with a good modulus false alarms are rare, and the expected running time is O(n+m)O(n + m). The same rolling hash powers plagiarism detection, the rsync file-synchronization tool and searches for many patterns at once.

Strings as numbers

Over the digits Σ={0,…,9}\Sigma = \{0, \ldots, 9\}, a window of mm characters is an mm-digit decimal number. Let pp be the value of the pattern and tst_s the value of T[s..s+m−1]T[s..s+m-1]. Then PP occurs with shift ss exactly when ts=pt_s = p. By Horner's rule pp costs Θ(m)\Theta(m) arithmetic operations, and moving the window one step is

ts+1=10(ts−10m−1 T[s])+T[s+m]:t_{s+1} = 10\left(t_s - 10^{m-1}\, T[s]\right) + T[s + m] :

drop the leading digit, shift, append the new digit. For a general alphabet of size dd, replace 10 by dd (for example d=256d = 256 for bytes).

The values have mm digits, too large to compare in constant time for long patterns. So compute everything modulo a prime qq: then every value fits in a machine word, with h=dm−1 mod qh = d^{m-1} \bmod q precomputed,

ts+1=(d (ts−T[s] h)+T[s+m]) mod q.t_{s+1} = \bigl(d\,(t_s - T[s]\,h) + T[s + m]\bigr) \bmod q .

Now ts≢p(modq)t_s \not\equiv p \pmod q proves the shift invalid, but ts≡pt_s \equiv p does not prove it valid: it may be a spurious hit, and the characters must be compared.

text
RABIN-KARP(T, P, d, q)
1  n = len(T); m = len(P)
2  h = d^(m-1) mod q
3  p = 0; t = 0
4  for i = 0 to m - 1                     // preprocessing: Theta(m)
5      p = (d * p + P[i]) mod q
6      t = (d * t + T[i]) mod q
7  for s = 0 to n - m
8      if p == t and P[0 .. m-1] == T[s .. s+m-1]
9          report s
10     if s < n - m
11         t = (d * (t - T[s] * h) + T[s + m]) mod q

The animation runs it on a digit string with q=11q = 11, small enough that spurious hits happen.

The program prints the same window hashes as the animation and counts the character comparisons spent on hits.

python · try it yourself
def rabin_karp(T, P, d=10, q=11, verbose=False):
    n, m = len(T), len(P)
    val = (lambda c: int(c)) if d == 10 else ord
    h = pow(d, m - 1, q)
    p = t = 0
    for i in range(m):
        p = (d * p + val(P[i])) % q
        t = (d * t + val(T[i])) % q
    found, spurious, comparisons = [], 0, 0
    for s in range(n - m + 1):
        if t == p:
            j = 0
            while j < m and T[s + j] == P[j]:
                j += 1
            comparisons += min(j + 1, m)
            if j == m:
                found.append(s)
            else:
                spurious += 1
            if verbose:
                print(f"  shift {s:2}: hash {t:2} = {p}, " + ("match" if j == m else "spurious hit"))
        elif verbose:
            print(f"  shift {s:2}: hash {t:2}")
        if s < n - m:
            t = (d * (t - val(T[s]) * h) + val(T[s + m])) % q
    return found, spurious, comparisons

print("pattern hash:", int("2639") % 11)
found, spurious, comps = rabin_karp("5172639187263915", "2639", verbose=True)
print("matches", found, "| spurious hits", spurious, "| character comparisons", comps)
pattern hash: 10
  shift  0: hash  2
  shift  1: hash 10 = 10, spurious hit
  shift  2: hash  3
  shift  3: hash 10 = 10, match
  shift  4: hash  0
  shift  5: hash  2
  shift  6: hash  2
  shift  7: hash  2
  shift  8: hash  3
  shift  9: hash  3
  shift 10: hash 10 = 10, match
  shift 11: hash  0
  shift 12: hash 10 = 10, spurious hit
matches [3, 10] | spurious hits 2 | character comparisons 10

Python's % always returns a value in [0,q)[0, q), even for the negative intermediate t−T[s]ht - T[s]h; in C or C++ the remainder of a negative number is negative, so the code adds qq before reducing (see the C++ version below).

How often are hits spurious?

With q=11q = 11 the window hash takes only 11 values, so about one shift in 11 collides with the pattern by accident. Choosing a large prime qq makes collisions rare. Heuristically, if the hashes behave like random values mod qq, the expected number of spurious hits is about (n−m+1)/q(n - m + 1)/q, and the expected running time is

O ⁣((n−m+1)+m (v+nq)),O\!\left((n - m + 1) + m\,\Bigl(v + \frac{n}{q}\Bigr)\right),

with vv the number of valid shifts. For q≥mq \ge m and few matches this is O(n+m)O(n + m). The worst case remains Θ((n−m+1)m)\Theta((n - m + 1)m), for example when every shift is valid (T=anT = a^n, P=amP = a^m), since then every hit must be checked.

The heuristic can be made rigorous by choosing the modulus at random among the primes up to a bound MM: a fixed spurious hit means that qq divides the nonzero difference ts−pt_s - p, which has fewer than mlg⁡dm \lg d prime factors, so a random prime is rarely one of them. Alternatively, fix a large prime and choose the base dd at random modulo qq; then two different windows collide with probability at most (m−1)/q(m - 1)/q, because their difference is a nonzero polynomial of degree below mm in dd.

python · try it yourself
import random

def rk_stats(T, P, q, d=256):
    n, m = len(T), len(P)
    h = pow(d, m - 1, q)
    p = t = 0
    for i in range(m):
        p = (d * p + ord(P[i])) % q
        t = (d * t + ord(T[i])) % q
    hits = valid = 0
    for s in range(n - m + 1):
        if t == p:
            hits += 1
            valid += T[s:s + m] == P
        if s < n - m:
            t = (d * (t - ord(T[s]) * h) + ord(T[s + m])) % q
    return hits - valid, valid

rng = random.Random(8)
T = "".join(rng.choice("abcd") for _ in range(50000))
P = T[31337:31337 + 10]
print("text 50000 random letters from abcd, pattern of length 10 taken from it")
for q in [7, 13, 101, 1009, 65521, 2**31 - 1]:
    spurious, valid = rk_stats(T, P, q)
    print(f"q = {q:10}: spurious hits {spurious:5} (expected about {(len(T) - 9) / q:8.1f}), valid shifts {valid}")
text 50000 random letters from abcd, pattern of length 10 taken from it
q =          7: spurious hits  7199 (expected about   7141.6), valid shifts 1
q =         13: spurious hits  3935 (expected about   3845.5), valid shifts 1
q =        101: spurious hits   513 (expected about    495.0), valid shifts 1
q =       1009: spurious hits    49 (expected about     49.5), valid shifts 1
q =      65521: spurious hits     1 (expected about      0.8), valid shifts 1
q = 2147483647: spurious hits     5 (expected about      0.0), valid shifts 1

Up to q=65521q = 65521 the counts follow the estimate (n−m+1)/q(n - m + 1)/q. The last line is a warning: the Mersenne prime q=231−1q = 2^{31} - 1 should give no spurious hits at all, yet it gives five. The reason is the base d=256=28d = 256 = 2^8: since 231≡1(modq)2^{31} \equiv 1 \pmod q, reducing mod qq just folds the 80-bit window value into 31-bit groups and adds them, so different windows collide far more often than random values would. Hash quality depends on the pair (d,q)(d, q), which is one more reason to pick the base at random.

Many patterns at once

Rabin-Karp extends naturally to searching for kk patterns of the same length: put the kk pattern hashes in a hash set and look up each window hash, for O(n+km)O(n + km) expected time. Two-dimensional matching (finding a small image in a large one) uses rolling hashes along rows and then along columns. For many patterns of different lengths, the Aho-Corasick automaton, a generalization of the next lesson's matcher, is the standard tool.

In C++

Rabin-Karp in C++ on bytes (d=256d = 256) with the prime q=1 000 000 007q = 1\,000\,000\,007. Products stay below 2632^{63} because every value is reduced mod qq before multiplying.

cpp · try it yourself
#include <cstdio>
#include <string>
#include <vector>

std::vector<int> rabin_karp(const std::string& T, const std::string& P, int& spurious) {
    const long long d = 256, q = 1000000007;
    int n = int(T.size()), m = int(P.size());
    std::vector<int> found;
    spurious = 0;
    if (m > n) return found;
    long long h = 1, p = 0, t = 0;
    for (int i = 0; i < m - 1; i++) h = h * d % q;
    for (int i = 0; i < m; i++) {
        p = (d * p + (unsigned char)P[i]) % q;
        t = (d * t + (unsigned char)T[i]) % q;
    }
    for (int s = 0; s + m <= n; s++) {
        if (t == p) {
            if (T.compare(s, m, P) == 0) found.push_back(s); else spurious++;
        }
        if (s + m < n) {
            t = (t - (unsigned char)T[s] * h % q + q) % q;        // keep it non-negative
            t = (t * d + (unsigned char)T[s + m]) % q;
        }
    }
    return found;
}

int main() {
    std::string T = "the cat sat on the mat; the cat ran", P = "the cat";
    int spurious;
    auto found = rabin_karp(T, P, spurious);
    std::printf("\"%s\" found at:", P.c_str());
    for (int s : found) std::printf(" %d", s);
    std::printf(" (spurious hits: %d)\n", spurious);
    found = rabin_karp("5172639187263915", "2639", spurious);
    std::printf("\"2639\" found at:");
    for (int s : found) std::printf(" %d", s);
    std::printf(" (spurious hits: %d)\n", spurious);
}
"the cat" found at: 0 24 (spurious hits: 0)
"2639" found at: 3 10 (spurious hits: 0)

With a modulus of a billion, the two spurious hits that q=11q = 11 produced disappear.

Test yourself

With d=10d = 10 and q=13q = 13, the window "314" has hash 314 mod 13=2314 \bmod 13 = 2. What is the hash of the next window "141" (the next text digit is 1)?

  1. 141 mod 13=11141 \bmod 13 = 11
  2. 22
  3. 00
  4. 55

What is a spurious hit?

  1. A match missed by the algorithm
  2. A shift where the window hash equals the pattern hash but the strings differ
  3. A hash value larger than qq
  4. A match at shift 0

What is the worst-case running time of Rabin-Karp?

  1. O(n+m)O(n + m)
  2. O(nlg⁡m)O(n \lg m)
  3. Θ((n−m+1)m)\Theta((n - m + 1)m)
  4. O(nq)O(nq)

Why does the rolling update take constant time?

  1. Because the hash ignores most characters
  2. Because the new hash follows from the old one by removing the leading character's contribution, multiplying by dd and adding the new character, all mod qq
  3. Because qq is prime
  4. Because the pattern is short