Numbers for text
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.
Turn the pattern into one small number, its hash. Read 653 as a number and keep the remainder after dividing by q = 13: 653 = 50 × 13 + 3, so hash(P) = 3. Python's % operator gives that remainder.
Do the same for the first 3 text digits: 314 = 24 × 13 + 2, so its hash is 2. 2 ≠ 3, so 314 cannot be 653. Skip this shift without comparing a single digit.
Rolling the window
Slide one digit right without reading 3 digits again: take away the 3 hundreds (314 → 14), multiply by the base d = 10 (140), add the new 1 (141). The same three moves work on the remainder alone: 2 becomes 11.
Each slide costs the same few steps, however long the pattern is. 141 becomes 415, hash 12. Still not 3: skip. The digit leaving is weighted by h = 10² mod 13 = 9, worked out once at the start.
Checking hash hits
Window 159 has hash 3, the same as the pattern. Equal hashes do not prove equal text: 159 and 653 differ by a multiple of 13. So check the digits: 1 ≠ 6. A false alarm, called a spurious hit.
Roll on: 592 has hash 7, skip. Then 926 has hash 3: another spurious hit, caught by the digit check (9 ≠ 6). With q = 13 there are only 13 possible hashes, so different windows often share one.
Roll twice more: 265 has hash 5, then 653 has hash 3. The hashes agree, so check the digits: 6, 5 and 3 all match. Rabin-Karp reports a match at shift 7, exactly where 653 sits.
8 windows, each hashed in a few steps; digits checked only on 3 hash hits. With a large prime q, wrong windows hit about 1 time in q, so the expected time is O(n + m). If every window hit, it would be O(nm).
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.