ENع
←Rabin-Karp
Lesson 48 · Strings and problem-solving patterns

Rabin-Karp and rolling hashes

14 min9 steps5 questionsAdvanced
About this lesson

Rabin-Karp searches text by comparing numbers instead of characters. It gives the pattern and every window of the text a small hash, the window read as a number and reduced mod a prime. Sliding the window one place updates the hash in a few steps, however long the pattern. Characters are checked only when the hashes agree, because two different windows can share a hash. Follow it through the first ten digits of π. It speeds up the method from "Naive string search", which compares every window digit by digit. The Software lessons "Strings: text in memory" and "Searching: linear and binary" cover the basics, and "Hash maps: finding things by key" introduces hashing.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 48 · Interactive
01 / 09

Find a pattern in 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.

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
Loading figure…
or ← →
Read the lesson step by step
  1. Find a pattern in 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.

    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
  2. Hash the pattern

    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.

    line 4:  p = int(P) % q
      int("653") = 653
      653 = 50 × 13 + 3
      p = 3
    
    a hash maps a long key to a small number;
    here every window lands in 0 .. 12
  3. Hash the first window

    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.

    line 4:  t = int(T[:m]) % q
      T[:3] = "314"
      314 = 24 × 13 + 2   t = 2
    
    line 6:  p == t ?
      3 == 2  no → skip shift 0
    equal text always has equal hashes, so unequal hashes prove a mismatch
  4. Roll 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.

    lines 9–10:  t = ((t − out·h)·d + new) % q
      h = 10^(m−1) mod 13 = 100 mod 13 = 9
      out = 3, new = 1
      ((2 − 3·9)·10 + 1) mod 13 = 11
      check: 141 = 10 × 13 + 11
    
    Python keeps the remainder non-negative even when t − out·h < 0
  5. Same cost every slide

    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.

    line 3:  h = pow(d, m − 1, q)   once
    line 10: one subtract, two multiplies, one add, one % per slide
      ((11 − 1·9)·10 + 5) mod 13 = 12
      3 == 12  no → skip shift 2
    
    recomputing the window from scratch would take m steps per shift
  6. A hash hit: check digits

    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.

      ((12 − 4·9)·10 + 9) mod 13 = 3
    line 6:  p == t  →  3 == 3  yes
             T[3:6] == P  →  "159" == "653"  no
      653 − 159 = 494 = 38 × 13
    
    spurious hit: equal hashes, different text
  7. Another false alarm

    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.

      ((3 − 1·9)·10 + 2) mod 13 = 7   skip
      ((7 − 5·9)·10 + 6) mod 13 = 3   hit
      "926" == "653"  no → spurious
    
    3 of 8 windows share hash 3: q = 13 is far too small
  8. A real match

    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.

      ((3 − 9·9)·10 + 5) mod 13 = 5   skip
      ((5 − 2·9)·10 + 3) mod 13 = 3   hit
      "653" == "653"  yes
    
    >>> rabin_karp("3141592653", "653")
    match at 7
  9. Cost: usually linear

    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).

    shift  window  hash                    result
      0   314   314 = 24 × 13 + 2   skip
      1   141   141 = 10 × 13 + 11   skip
      2   415   415 = 31 × 13 + 12   skip
      3   159   159 = 12 × 13 + 3   hit → digits differ (spurious)
      4   592   592 = 45 × 13 + 7   skip
      5   926   926 = 71 × 13 + 3   hit → digits differ (spurious)
      6   265   265 = 20 × 13 + 5   skip
      7   653   653 = 50 × 13 + 3   hit → digits match
    
    hash the pattern and first window: O(m)
    roll n − m times: O(1) each
    check a hit: O(m), so many spurious hits → O(nm) worst case
    real code uses a large random prime q (algs4: 31-bit) and d = 256

Quiz Unlocks after the last step.