25. Rabin-Karp String Search
Rolling hashes for fast pattern matching
You need to find every occurrence of a pattern in a text. The brute-force approach checks the pattern against every position — O(n × m) in the worst case. KMP and Aho-Corasick solve this with clever automata. But there's a beautifully different approach: instead of comparing characters, compare hashes.
The Rabin-Karp algorithm (1987) computes a hash of the pattern, then slides a window across the text, maintaining a rolling hash that updates in O(1) as the window moves. When hashes match, it verifies with a full comparison. The key insight: most positions won't match, so most comparisons are just cheap integer comparisons instead of expensive character-by-character checks.
The Problem
Given a text of length n and a pattern of length m, find all positions where the pattern occurs in the text. We want to do this faster than the O(n × m) brute-force approach.
The Idea: Hash and Compare
The Rabin-Karp Strategy
Compute the hash of the pattern. Then compute the hash of every m-character window in the text. If a window's hash matches the pattern's hash, verify character by character. If it doesn't match, slide the window one position to the right — and update the hash in O(1) instead of recomputing it from scratch.
The trick is the rolling hash: a hash function designed so that when you slide the window by one character (remove the leftmost, add a new rightmost), you can compute the new hash from the old one in constant time.
The Rolling Hash
Rabin-Karp uses a polynomial rolling hash. Treat each character as a digit in a base-d number (where d is the alphabet size), and take the result modulo a prime q:
Polynomial hash
hash("abc") = (a × d² + b × d¹ + c × d⁰) mod q
With d = 256 (ASCII) and characters a=97, b=98, c=99:
hash("abc") = (97 × 256² + 98 × 256 + 99) mod q
When the window slides one position right — dropping the leftmost character old and adding a new rightmost character new — the hash updates in O(1):
Rolling hash update
newHash = (d × (oldHash - old × d^(m-1)) + new) mod q
Subtract the contribution of the outgoing character, shift everything left (multiply by d), and add the incoming character. One multiplication, one subtraction, one addition, one mod — all O(1).
Worked Example
Find "DAD" in "ABCDABD"
Pattern: "DAD" (length m = 3)
Text: "ABCDABD"
Using d = 256, q = 101 (a small prime for illustration)
Character values: A=65, B=66, C=67, D=68
Pattern hash:
hash("DAD") = (68×256² + 65×256 + 68) mod 101
= (4456448 + 16640 + 68) mod 101
= 4473156 mod 101
= 36
Precompute h = d^(m-1) mod q = 256² mod 101 = 65536 mod 101 = 82
Window 1: "ABC"
hash = (65×256² + 66×256 + 67) mod 101
= (4259840 + 16896 + 67) mod 101
= 4276803 mod 101 = 73
73 ≠ 36 → no match
Window 2: "BCD" — roll the hash
hash = (256 × (73 - 65×82) + 68) mod 101
= (256 × (73 - 5330) + 68) mod 101
work mod 101: 65×82 mod 101 = 5330 mod 101 = 78
(256 × (73 - 78) + 68) mod 101
= (256 × (-5) + 68) mod 101
= (-1280 + 68) mod 101
= -1212 mod 101 = 101 - (1212 mod 101) = 101 - 0 = 0
0 ≠ 36 → no match
Window 3: "CDA"
Roll hash from previous...
≠ 36 → no match
Window 4: "DAB"
Roll hash...
≠ 36 → no match
Window 5: "ABD"
Roll hash...
≠ 36 → no match
No occurrence of "DAD" found.
Let's try a case where we do find a match:
Find "AB" in "AABAC"
Pattern: "AB" (m = 2)
Text: "AABAC"
d = 256, q = 101
hash("AB") = (65×256 + 66) mod 101 = 16706 mod 101 = 43
h = d^(m-1) mod q = 256 mod 101 = 54
Window 1: "AA"
hash = (65×256 + 65) mod 101 = 16705 mod 101 = 42
42 ≠ 43 → skip
Window 2: "AB"
hash = (256×(42 - 65×54) + 66) mod 101
65×54 mod 101 = 3510 mod 101 = 75
(256×(42 - 75) + 66) mod 101
= (256×(-33) + 66) mod 101
= (-8448 + 66) mod 101
= -8382 mod 101 = 43
43 == 43 → HASH MATCH! Verify: text[1..2] = "AB" == "AB" ✓
Found at position 1!
Window 3: "BA"
Roll hash... ≠ 43 → skip
Window 4: "AC"
Roll hash... ≠ 43 → skip
Result: pattern found at position 1
The Algorithm
-
Compute the pattern hash
Hash the pattern string using the polynomial hash.
-
Compute the first window hash
Hash the first m characters of the text.
-
Slide and compare
For each window position: if the hash matches the pattern hash, verify character by character (to rule out hash collisions). Then roll the hash to the next window position in O(1).
Pseudocode
function rabinKarp(text, pattern, d, q):
n = text.length
m = pattern.length
h = d^(m-1) mod q // precompute
pHash = 0 // pattern hash
tHash = 0 // text window hash
results = []
// Compute initial hashes
for i = 0 to m-1:
pHash = (d × pHash + pattern[i]) mod q
tHash = (d × tHash + text[i]) mod q
// Slide the window
for i = 0 to n-m:
if pHash == tHash:
if text[i..i+m-1] == pattern: // verify
results.append(i)
// Roll the hash (if not at last position)
if i < n-m:
tHash = (d × (tHash - text[i] × h) + text[i+m]) mod q
if tHash < 0:
tHash += q
return results
Choosing the Prime q
The prime q determines how many spurious hits (hash collisions) we get. A larger prime means fewer collisions but larger intermediate values.
| Prime size | False positive rate | Notes |
|---|---|---|
| Small (101) | High | Good for teaching, bad for practice |
| Medium (10⁷) | Low | Fits in 64-bit arithmetic with d=256 |
| Large (10⁹ + 7) | Very low | Standard competitive programming prime |
In practice, using a 64-bit prime makes spurious hits extremely rare — essentially O(1) expected false positives over the entire text.
Complexity
Complexity
Expected time: O(n + m) — the rolling hash processes each
character once, and spurious hits are rare with a good prime.
Worst case: O(n × m) — if every window produces a hash
collision (all hashes equal), every position requires a full verification.
This is astronomically unlikely with a good prime.
Space: O(1) — beyond the input, only a few variables.
Multiple Pattern Search
One of Rabin-Karp's unique strengths: searching for multiple patterns simultaneously. Compute the hash of each pattern and store them in a hash set. At each window position, check the text hash against the set in O(1). This finds all occurrences of k patterns in O(n + km) expected time — competitive with Aho-Corasick for moderate k.
Multi-pattern Rabin-Karp
Patterns: {"AB", "CD", "EF"}
Pattern hashes: {43, 87, 12} (stored in a hash set)
For each window in the text:
if hash(window) in {43, 87, 12}:
verify which pattern matched
One pass over the text, regardless of how many patterns!
Comparison with Other String Matching Algorithms
| Algorithm | Preprocessing | Search time | Best for |
|---|---|---|---|
| Brute force | None | O(nm) | Very short patterns |
| KMP | O(m) | O(n) | Single pattern, guaranteed linear |
| Rabin-Karp | O(m) | O(n) expected | Multiple patterns, plagiarism detection |
| Aho-Corasick | O(Σm) | O(n + matches) | Many patterns, guaranteed linear |
Rabin-Karp's advantage isn't raw speed for a single pattern — KMP is better there. Its strength is simplicity and multi-pattern search without building an automaton.
Where Rabin-Karp Is Used
| Application | How it uses Rabin-Karp |
|---|---|
| Plagiarism detection | Hash overlapping n-grams of two documents; matching hashes indicate shared passages |
| Git diff | Rolling hashes identify matching chunks between file versions |
| rsync | Rolling checksums find matching blocks between local and remote files to minimize data transfer |
| Intrusion detection | Scan network traffic for multiple known attack signatures simultaneously |
| Bioinformatics | Search for DNA motifs in genome sequences |
Key Takeaways
- Rabin-Karp hashes the pattern and each text window, comparing hashes instead of characters
- The rolling hash updates in O(1) as the window slides: subtract the outgoing character, shift, add the incoming character
- Hash matches require verification to rule out collisions — but collisions are rare with a good prime
- Expected O(n + m) time, O(nm) worst case (virtually never hit in practice)
- Uniquely suited for multiple pattern search: hash all patterns, check each window against the set
- The rolling hash concept extends far beyond string matching: rsync, deduplication, content-defined chunking
Try It Yourself — Rabin-Karp
Enter a text and a pattern. Step through the algorithm and watch the rolling hash value update as the window slides. Hash matches are highlighted for verification, and confirmed matches are marked in green.
Rabin-Karp is the string matching algorithm that thinks like a systems engineer: instead of clever automata, it uses hashing — the same tool that powers hash tables, content addressing, and data deduplication. The rolling hash idea is especially elegant: by choosing a multiplicative hash, we turn the "slide a window by one character" operation into a constant-time arithmetic update. This same trick shows up in rsync, git's delta compression, and content-defined chunking for backup systems. If you enjoyed this, the Hash Tables article covers the foundational data structure, and KMP shows the automaton-based approach to the same problem.