03112431455962768593P[0]6P[1]5P[2]3hash(P)windowhash(win)011def rabin_karp(T, P, d=10, q=13):2 n, m = len(T), len(P)3 h = pow(d, m - 1, q)4 p, t = int(P) % q, int(T[:m]) % q5 for s in range(n - m + 1):6 if p == t and T[s:s+m] == P:7 print("match at", s)8 if s + m < n:9 out, new = int(T[s]), int(T[s+m])10 t = ((t - out * h) * d + new) % q
Boxes: the text, the pattern and the hashes (mod 13)Frame: the current window of three digitsHopping digits: the rolling update, one leaves and one arrivesThe text 3141592653 at the back; the frame marks the current window of three digits. Each window's hash is the window read as a number, mod 13. A slide drops the leaving digit and adds the arriving one, so the hash rolls in a few steps. Equal hashes send the window to the digit check: 159 and 926 are spurious hits, 653 at shift 7 is the match.

Numbers for text

  1. Find the pattern 653 in the text 3141592653, the first ten digits of π. The naive way lines the pattern up at each of the 8 shifts and compares digit by digit. Rabin-Karp compares one small number per shift instead.

Rolling the window

Checking hash hits

What happens

;; step 1/9 · the-task
text T = "3141592653"   n = 10
pattern P = "653"   m = 3
shifts s = 0 .. n − m = 0 .. 7   (8 windows)

naive search: compare P with T[s:s+m] digit by digit at every shift,
up to m comparisons each, so up to (n − m + 1)·m in the worst case

q = 13 is chosen tiny so you can follow the arithmetic, and it causes 2 spurious hits in 8 windows. On a ten-digit text the naive search is just as quick (it makes 10 digit comparisons here); Rabin-Karp pays off when the pattern is long or when you search for many patterns at once. CLRS chapter 32.2 gives Θ(m) preprocessing and Θ((n − m + 1)m) matching time in the worst case; with few valid shifts and a large prime q the expected matching time is O(n + m). The algs4 slides put the chance of a collision at about 1/Q.