Algorithms · String Matching: Naive Search and Rabin-Karp
Rabin-Karp
3.1 The idea
Instead of comparing characters at every shift, compare a hash of the window with the hash of the pattern. Only when the hashes agree do we verify character by character. The magic is that the window hash can be updated in when the window slides by one.
3.2 The polynomial hash
Interpret a length- string (each mapped to a digit in ) as a base- number:
For the window starting at :
We reduce everything modulo a prime so the numbers fit in a machine word. All arithmetic below is mod .
3.3 The rolling-hash recurrence (the heart of the algorithm)
When the window slides from to , we drop (which carried weight ) and append (weight ):
Why each term: multiply by shifts every remaining digit one place left (weight ); subtracting removes the outgoing digit before the multiply (equivalently, after multiplying by one would subtract ); adding inserts the new digit at weight .
Precomputation: costs (Horner's rule), and is computed once by fast exponentiation in . Then each of the slides costs .
3.4 The algorithm
RABIN-KARP(T, P, d, q)
n = length(T); m = length(P)
hP = 0; hT = 0; h = d^(m-1) mod q // h = d^{m-1} mod q
for i = 0 to m-1
hP = (d*hP + P[i]) mod q
hT = (d*hT + T[i]) mod q
for s = 0 to n-m
if hP == hT
if T[s..s+m-1] == P // verify to rule out spurious hit
print "Pattern occurs at shift" s
if s < n-m
hT = (d*(hT - T[s]*h) + T[s+m]) mod q
3.5 Spurious hits
If but the window is not equal to , we call it a spurious hit (false positive). It happens because different strings can share a residue mod . Spurious hits are caught by the explicit verification step, so they never cause a wrong answer — only extra work.
- Expected running time: . If is a large prime (say , chosen so that fits in a machine word), the probability that a random non-matching window collides is about , so the expected number of spurious hits over windows is , negligible. Total expected cost .
- Worst case: . If many windows trigger verification, each verification costs up to comparisons, giving . This happens for genuinely matching text such as , (every shift is a true match), or for an adversarial input with many spurious hits. In general the expected time is where is the number of valid shifts.
- Space: extra (just a few integers).
3.6 Comparison table
| Feature | Naive | Rabin-Karp |
|---|---|---|
| Preprocessing | (hash of ) + for | |
| Matching (expected, random text) | ||
| Matching (worst) | ||
| Extra space | ||
| Key idea | compare characters | compare hashes, verify on hit |
| Sensitive to | repetitive text | choice of (spurious hits) |