Rabin-Karp and rolling hashes
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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
اقرأ الدرس خطوة بخطوة
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 caseHash 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 .. 12Hash 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 mismatchRoll 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 < 0Same 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 shiftA 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 textAnother 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 smallA 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 7Cost: 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01With d = 10 and q = 13, what is the hash of the window 415?
415 = 31 × 13 + 12, so 415 mod 13 = 12. The hash keeps only the remainder.
02The window 314 has hash 2 (mod 13) and h = 10² mod 13 = 9. Sliding right brings in the digit 1. What does ((2 − 3·9)·10 + 1) mod 13 give?
(2 − 27)·10 + 1 = −249, and −249 mod 13 = 11 (Python's % gives a non-negative result here). That matches 141 mod 13 = 11, computed from scratch.
03Window 159 and the pattern 653 both hash to 3 (mod 13). What should Rabin-Karp do?
Equal hashes only say the window might match. 653 − 159 = 494 = 38 × 13, so the remainders agree while the digits do not. The character check catches it.
04Why does real code use a large prime q instead of 13?
With q = 13 there are only 13 possible hashes, and 3 of the 8 windows here hit. With a large prime q, a wrong window collides about 1 time in q, so the expected running time stays O(n + m).
05What is Rabin-Karp's worst-case running time, with the character check, for text length n and pattern length m?
If every window's hash hits (for example, text and pattern made of one repeated character), each of the n − m + 1 windows needs an O(m) check: O(nm) in total. That is unlikely with a large random prime.
المسرد
- Pattern (P)
- The short string you are looking for. Its length is m.
- Text (T)
- The long string you search in. Its length is n.
- Shift (s)
- Where the pattern is lined up against the text: the window T[s:s+m]. There are n − m + 1 shifts.
- Base (d)
- The number of different digits, also called the radix. Decimal digits use d = 10, so a window like 314 means 3·10² + 1·10 + 4.
- Hash
- A small number computed from a longer key. Here: the window read as a number, mod q.
- Modulus (q)
- The number you divide by to keep only the remainder. Rabin-Karp uses a prime.
- Rolling hash
- A hash that can be updated in a few steps when one character leaves the window and another arrives.
- Spurious hit
- A window whose hash equals the pattern's hash although the text is different. Also called a false positive.
الملاحظات والمصادر
- 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.
- Letters work the same way: treat each character code (Python ord(c)) as a digit in base d = 256. Sedgewick and Wayne use R = 256 and a random 31-bit prime Q.
- 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.
- The code is real Python 3: rabin_karp("3141592653", "653") prints "match at 7". It reads digits with int(), so it only takes digit strings. Python's % keeps the result non-negative for a positive q, so t − out·h may go below zero safely. In C or Java, reduce out·h mod q first, then add q before taking %: (t + q − (out·h) % q) % q, as RabinKarp.java does.
- Richard Karp and Michael Rabin published the algorithm in 1987 in the IBM Journal of Research and Development.
- Sedgewick and Wayne, Algorithms 4th ed., §5.3 Substring Search
- Sedgewick and Wayne, RabinKarp.java
- Sedgewick and Wayne, lecture slides 5.3 Substring Search (Rabin-Karp analysis)
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 9: Table Doubling, Karp-Rabin
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §32.2 The Rabin-Karp algorithm
- Rabin-Karp algorithm (overview; Karp and Rabin, IBM Journal of Research and Development, 1987)
- Python Language Reference: Binary arithmetic operations (the % operator)
- Python Built-in Functions: pow() and int()
اختبار يتاح بعد الخطوة الأخيرة.