Rabin–Karp
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Rabin-Karp slides a window along the text and keeps a fingerprint number of what is inside the window. When the window moves one step, it adjusts the number slightly instead of recomputing it. Only windows whose fingerprint matches the pattern get a real letter-by-letter check.
Practical use cases
- Web app: Plagiarism check for student essays. A college portal compares each submitted essay against a bank of known copied passages. Instead of comparing every sentence against every passage, it slides a window over the essay, keeps a quick fingerprint, and looks it up in a set of fingerprints of the known passages. Only a handful of real matches need a closer look.
- Web app: Finding many banned words at once. A comment system must flag any of 200 blocked phrases of the same length. Running 200 separate searches over every comment is slow. With one rolling fingerprint per window and a set of the 200 fingerprints, each comment is scanned once, and a match is a single set lookup.
- System: Duplicate file and sync tools. Backup and sync tools split big files into chunks by rolling a fingerprint over the bytes and cutting where it hits a certain value. Because the fingerprint updates cheaply as the window slides, a file edited in the middle still shares most of its chunks with the old version, and only the changed chunks are sent again.
The story: The Receipt Rolling Trick
Raju kept a very long roll of cash-memo codes from the week, and he needed to find where the code DAB appeared. Comparing letters at every position tired his eyes. Mira said, "Give each three-letter window a fingerprint number instead. Compare numbers, not letters."
"But making a fingerprint for every window means reading three letters every time!" complained Kabir. "That is no better." Mira smiled: "Not if the window rolls. When it slides one step, one letter leaves and one letter arrives. Take the old fingerprint, remove the leaver's share, shift, and add the newcomer. Just a couple of quick sums."
Only when the window's number matched the pattern's number did Raju read the real letters to confirm. In a long roll, that almost never happened by accident, so most windows cost a tiny bit of work. This is Rabin-Karp: pattern matching with a rolling hash. Its real superpower shows when you search for many patterns at once.
How to spot this problem, and where you need it
You need to look for many patterns, or many equal-length pieces, inside a large text, and comparing letter by letter for each one is too slow.
Signs you need it
- The task is "does any of these K phrases appear in this text?" with K in the hundreds or thousands.
- You compare fixed-length substrings of a big string and keep recomputing something for each one from scratch.
- The problem is about duplicate substrings or matching sections between two large texts or files.
Where to use it in a project
- Plagiarism or duplicate-content detection across essays, articles or product descriptions.
- Moderation filters that check a list of fixed-length banned phrases in comments or messages.
- File-sync and deduplication tools that find shared chunks between versions.
The solution
Choose a window the same length as the pattern. Compute its fingerprint number. Slide one step: remove the contribution of the letter that left, add the letter that entered, which is a quick update rather than a full recomputation. Whenever the fingerprint equals the pattern fingerprint, confirm with a real comparison to rule out a rare false alarm. For many patterns, keep their fingerprints in a set.
Payoff: Before: 200 phrases times a 10,000-word comment meant millions of comparisons. After: one pass over the comment with one set lookup per position.
Explain it like I am 8
Instead of reading a whole word every time, give each word a number tag. Slide a window along; when it moves, change the tag a little (drop the old letter, add the new one) instead of making it from scratch. Only if two tags are the same do you read the words to check.
How it works, step by step
- Fingerprint the pattern once (the string-hash recipe from before).
- Fingerprint the first window of the text (same length as the pattern).
- If the numbers match, compare the real letters (this rules out collisions). If they do not, skip this window.
- Roll the window: remove the leaving letter's share, multiply by the base, add the entering letter, wrap with the remainder.
- Repeat until the window reaches the end of the text.
The code in four languages
PHP
<?php
// Rabin-Karp: compare rolling fingerprints, verify only on a match.
function rabinKarp(string $text, string $pattern): array {
$n = strlen($text);
$m = strlen($pattern);
if ($m === 0 || $m > $n) { return []; }
$base = 31;
$mod = 1000003;
$pow = 1; // weight of the leaving letter
for ($i = 1; $i < $m; $i++) { $pow = ($pow * $base) % $mod; }
$pHash = 0;
$wHash = 0;
for ($i = 0; $i < $m; $i++) { // fingerprint pattern and first window
$pHash = ($pHash * $base + ord($pattern[$i])) % $mod;
$wHash = ($wHash * $base + ord($text[$i])) % $mod;
}
$found = [];
for ($s = 0; $s + $m <= $n; $s++) {
if ($wHash === $pHash && substr($text, $s, $m) === $pattern) {
$found[] = $s; // fingerprints equal AND letters equal
}
if ($s + $m < $n) { // roll the window one step
$wHash = ($wHash - (ord($text[$s]) * $pow) % $mod + $mod) % $mod;
$wHash = ($wHash * $base + ord($text[$s + $m])) % $mod;
}
}
return $found;
}
echo json_encode(rabinKarp("ABCDABC", "DAB")) . "\n"; // [3]
echo json_encode(rabinKarp("AAAAA", "AA")) . "\n"; // [0,1,2,3]JavaScript
// Rabin-Karp: compare rolling fingerprints, verify only on a match.
function rabinKarp(text, pattern) {
const n = text.length;
const m = pattern.length;
if (m === 0 || m > n) { return []; }
const base = 31;
const mod = 1000003;
let pow = 1; // weight of the leaving letter
for (let i = 1; i < m; i++) { pow = (pow * base) % mod; }
let pHash = 0;
let wHash = 0;
for (let i = 0; i < m; i++) { // fingerprint pattern and first window
pHash = (pHash * base + pattern.charCodeAt(i)) % mod;
wHash = (wHash * base + text.charCodeAt(i)) % mod;
}
const found = [];
for (let s = 0; s + m <= n; s++) {
if (wHash === pHash && text.substr(s, m) === pattern) {
found.push(s); // fingerprints equal AND letters equal
}
if (s + m < n) { // roll the window one step
wHash = (wHash - (text.charCodeAt(s) * pow) % mod + mod) % mod;
wHash = (wHash * base + text.charCodeAt(s + m)) % mod;
}
}
return found;
}
console.log(JSON.stringify(rabinKarp('ABCDABC', 'DAB'))); // [3]
console.log(JSON.stringify(rabinKarp('AAAAA', 'AA'))); // [0,1,2,3]Java
import java.util.*;
public class Main {
// Rabin-Karp: compare rolling fingerprints, verify only on a match.
static List<Integer> rabinKarp(String text, String pattern) {
int n = text.length();
int m = pattern.length();
List<Integer> found = new ArrayList<>();
if (m == 0 || m > n) { return found; }
long base = 31;
long mod = 1000003;
long pow = 1; // weight of the leaving letter
for (int i = 1; i < m; i++) { pow = (pow * base) % mod; }
long pHash = 0;
long wHash = 0;
for (int i = 0; i < m; i++) { // fingerprint pattern and first window
pHash = (pHash * base + pattern.charAt(i)) % mod;
wHash = (wHash * base + text.charAt(i)) % mod;
}
for (int s = 0; s + m <= n; s++) {
if (wHash == pHash && text.startsWith(pattern, s)) {
found.add(s); // fingerprints equal AND letters equal
}
if (s + m < n) { // roll the window one step
wHash = (wHash - (text.charAt(s) * pow) % mod + mod) % mod;
wHash = (wHash * base + text.charAt(s + m)) % mod;
}
}
return found;
}
public static void main(String[] args) {
System.out.println(rabinKarp("ABCDABC", "DAB")); // [3]
System.out.println(rabinKarp("AAAAA", "AA")); // [0, 1, 2, 3]
}
}Go
package main
import "fmt"
// rabinKarp compares rolling fingerprints and verifies only on a match.
func rabinKarp(text, pattern string) []int {
n, m := len(text), len(pattern)
if m == 0 || m > n {
return nil
}
const base = 31
const mod = 1000003
pow := 1 // weight of the leaving letter
for i := 1; i < m; i++ {
pow = (pow * base) % mod
}
pHash, wHash := 0, 0
for i := 0; i < m; i++ { // fingerprint pattern and first window
pHash = (pHash*base + int(pattern[i])) % mod
wHash = (wHash*base + int(text[i])) % mod
}
var found []int
for s := 0; s+m <= n; s++ {
if wHash == pHash && text[s:s+m] == pattern {
found = append(found, s) // fingerprints equal AND letters equal
}
if s+m < n { // roll the window one step
wHash = (wHash - (int(text[s])*pow)%mod + mod) % mod
wHash = (wHash*base + int(text[s+m])) % mod
}
}
return found
}
func main() {
fmt.Println(rabinKarp("ABCDABC", "DAB")) // [3]
fmt.Println(rabinKarp("AAAAA", "AA")) // [0 1 2 3]
}Time: O(n + m) on average · O(n × m) worst case · Extra space: O(1). Rolling makes each window cost a few operations. The worst case needs many collisions, which a good big modulus makes very rare.
Watch out for
- Trusting equal fingerprints without checking the real letters. A collision would give a wrong answer.
- Letting the subtraction go negative when rolling. Add the modulus back before taking the remainder, as the code does.
- Choosing a tiny modulus, which causes many false alarms and brings back the slow worst case.
Quick check
- When the window rolls one step, what happens to the fingerprint?
- It is recomputed from scratch
- The leaving letter is removed and the new one added
- It stays the same
- The fingerprints match. What next?
- Report a match straight away
- Skip this window
- Compare the real letters to confirm
- What is Rabin-Karp especially good at?
- Searching for many patterns at once
- Sorting words
- Reversing strings