AlgoTales · Roadmap

Rabin-Karp

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Rabin-Karp compares short numeric fingerprints (hashes) of text pieces instead of the pieces themselves. If the fingerprints differ, the texts surely differ; if they match, a quick real check confirms. It is especially good when searching for many patterns at once.

Practical use cases

  • Web app: Catching copied paragraphs in assignments. A college portal checks submitted essays against previous ones. Each paragraph is turned into a fingerprint, and equal fingerprints flag a likely copy. Comparing numbers is far quicker than comparing paragraphs word by word across thousands of submissions. Reviewers only look at the few paragraphs whose fingerprints match, which saves hours across a whole class.
  • Web app: Finding duplicate uploads. A document-storage site wants to detect when two files share large identical chunks. It stores a fingerprint per chunk and only looks closer when two fingerprints are equal. This saves storage and upload time, because most chunks are recognised by number instead of by comparing full content.
  • System: Multi-pattern and image search. Searching for many keywords at once, or for a small image patch inside a larger picture, works well with fingerprints because each window is checked with one number comparison. Checking many patterns costs about the same as checking one, since each window is compared with a set of numbers.

The story: The Kirana Store Fingerprints

The kirana store of Raju's uncle had thousands of bills, and the tax officer asked: "Find every bill that contains the code word CAD." Comparing the word letter by letter against every spot of every bill was exhausting. Zoya, who worked the counter, had a cheaper idea.

"Give every 3-letter piece a fingerprint, a single small number made from its letters. Comparing two numbers is instant." She worked out the fingerprint of CAD once. Then, for each window on a bill, she only looked at the letters if the fingerprint matched. If the numbers differ, the words surely differ.

The clever part: moving the window by one letter does not need a fresh calculation. The old fingerprint can be rolled: take away the share of the letter that left, shift everything over, and add the letter that arrived. Sometimes two different words share a fingerprint by bad luck (a collision), so Zoya always double-checked the letters on a match. That is Rabin-Karp.

How to spot this problem, and where you need it

You must find many pieces of text, or detect copies, inside a lot of other text, and comparing character by character is too slow.

Signs you need it

  • You are doing plagiarism, duplicate or near-duplicate detection across many documents.
  • There are many patterns to look for at once, not just one.
  • Every comparison between long strings is costly, but comparing numbers would be cheap.
  • The problem mentions hashing, or windows of fixed length.

Where to use it in a project

  • Plagiarism and duplicate-content checks in portals and CMS tools.
  • Search features that look for any of a set of equal-length phrases.

The solution

Turn the pattern into a number (a hash) using its letters. Slide a window of the same length along the text, computing the hash of each window quickly from the previous one. Only when a window hash equals the pattern hash do you compare the actual letters to rule out a false alarm. Most windows are rejected with one number comparison.

Payoff: Before: comparing every window letter by letter. After: one number comparison per window, with rare real checks.

Explain it like I am 8

Instead of comparing two whole words, compare two "ID cards" made from them. If the ID cards are different, the words are different, done! If the ID cards are equal, take a quick look at the real words to be sure, because two people can sometimes share a number.

How it works, step by step

  1. Turn the pattern into one small number with a fingerprint function (letters mixed together, then reduced with a remainder so it stays small).
  2. Fingerprint the first window of the text, same length as the pattern.
  3. If the two numbers differ, skip this window for free. If they are equal, compare real letters to confirm (collisions are possible).
  4. Roll to the next window: remove the leaving letter's share, shift, add the entering letter. No re-reading of the whole window.
  5. Repeat to the end of the text and collect every confirmed start position.

The code in four languages

PHP

<?php
// Rabin-Karp: roll a small fingerprint over every window of the text.
function rabinKarp(string $t, string $p): array {
    $n = strlen($t); $m = strlen($p);
    if ($m === 0 || $m > $n) return [[], 0];
    $B = 256; $M = 101;                         // base and a small prime to keep numbers small
    $P = 1;                                     // share of the leftmost letter in a window
    for ($i = 0; $i < $m - 1; $i++) $P = ($P * $B) % $M;
    $hp = 0; $ht = 0;
    for ($i = 0; $i < $m; $i++) {
        $hp = ($hp * $B + ord($p[$i])) % $M;
        $ht = ($ht * $B + ord($t[$i])) % $M;
    }
    $res = []; $fake = 0;
    for ($s = 0; $s + $m <= $n; $s++) {
        if ($hp === $ht) {                      // fingerprints agree: verify letters
            if (substr($t, $s, $m) === $p) $res[] = $s; else $fake++;
        }
        if ($s + $m < $n) {                     // roll: drop t[s], add t[s+m]
            $ht = (($ht - ord($t[$s]) * $P % $M + $M) * $B + ord($t[$s + $m])) % $M;
        }
    }
    return [$res, $fake];
}
[$found, $fake] = rabinKarp("abracadabra", "cad");
echo implode(",", $found), " false alarms: ", $fake, "\n";   // 4 false alarms: 0

JavaScript

// Rabin-Karp: roll a small fingerprint over every window of the text.
function rabinKarp(t, p) {
  const n = t.length, m = p.length;
  if (m === 0 || m > n) return [[], 0];
  const B = 256, M = 101;                       // base and a small prime to keep numbers small
  let P = 1;                                    // share of the leftmost letter in a window
  for (let i = 0; i < m - 1; i++) P = (P * B) % M;
  let hp = 0, ht = 0;
  for (let i = 0; i < m; i++) {
    hp = (hp * B + p.charCodeAt(i)) % M;
    ht = (ht * B + t.charCodeAt(i)) % M;
  }
  const res = []; let fake = 0;
  for (let s = 0; s + m <= n; s++) {
    if (hp === ht) {                            // fingerprints agree: verify letters
      if (t.substr(s, m) === p) res.push(s); else fake++;
    }
    if (s + m < n) {                            // roll: drop t[s], add t[s+m]
      ht = ((ht - (t.charCodeAt(s) * P) % M + M) * B + t.charCodeAt(s + m)) % M;
    }
  }
  return [res, fake];
}
const [found, fake] = rabinKarp("abracadabra", "cad");
console.log(found.join(",") + " false alarms: " + fake);   // 4 false alarms: 0

Java

import java.util.*;

public class Main {
    record Result(List<Integer> found, int fake) {}

    // Rabin-Karp: roll a small fingerprint over every window of the text.
    static Result rabinKarp(String t, String p) {
        int n = t.length(), m = p.length();
        if (m == 0 || m > n) return new Result(List.of(), 0);
        int B = 256, M = 101;                       // base and a small prime to keep numbers small
        int P = 1;                                  // share of the leftmost letter in a window
        for (int i = 0; i < m - 1; i++) P = (P * B) % M;
        int hp = 0, ht = 0;
        for (int i = 0; i < m; i++) {
            hp = (hp * B + p.charAt(i)) % M;
            ht = (ht * B + t.charAt(i)) % M;
        }
        List<Integer> res = new ArrayList<>();
        int fake = 0;
        for (int s = 0; s + m <= n; s++) {
            if (hp == ht) {                         // fingerprints agree: verify letters
                if (t.startsWith(p, s)) res.add(s); else fake++;
            }
            if (s + m < n) {                        // roll: drop t[s], add t[s+m]
                ht = ((ht - t.charAt(s) * P % M + M) * B + t.charAt(s + m)) % M;
            }
        }
        return new Result(res, fake);
    }

    public static void main(String[] args) {
        Result r = rabinKarp("abracadabra", "cad");
        System.out.println(r.found() + " false alarms: " + r.fake());   // [4] false alarms: 0
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// rabinKarp rolls a small fingerprint over every window of the text.
// It returns the match positions and how many fingerprint matches were false alarms.
func rabinKarp(t, p string) ([]int, int) {
	n, m := len(t), len(p)
	if m == 0 || m > n {
		return nil, 0
	}
	const B, M = 256, 101 // base and a small prime to keep numbers small
	P := 1                // share of the leftmost letter in a window
	for i := 0; i < m-1; i++ {
		P = (P * B) % M
	}
	hp, ht := 0, 0
	for i := 0; i < m; i++ {
		hp = (hp*B + int(p[i])) % M
		ht = (ht*B + int(t[i])) % M
	}
	var res []int
	fake := 0
	for s := 0; s+m <= n; s++ {
		if hp == ht { // fingerprints agree: verify letters
			if t[s:s+m] == p {
				res = append(res, s)
			} else {
				fake++
			}
		}
		if s+m < n { // roll: drop t[s], add t[s+m]
			ht = ((ht-int(t[s])*P%M+M)*B + int(t[s+m])) % M
		}
	}
	return res, fake
}

func main() {
	found, fake := rabinKarp("abracadabra", "cad")
	fmt.Println(strings.Trim(fmt.Sprint(found), "[]"), "false alarms:", fake) // 4 false alarms: 0
}

Time: O(n + m) average, O(n × m) worst · Extra space: O(1). Rolling makes each window cost a few steps; only unlucky collisions force extra letter checks.

Watch out for

  • Trusting the fingerprint without checking letters. Two different words can share a number.
  • Forgetting the "+ M" before the remainder, so a negative number sneaks in (very visible in PHP and JavaScript).
  • Recomputing each window from scratch, which loses the whole speed-up.

Quick check

  1. Two windows have different fingerprints. What do we know?
    • They might still be equal
    • They are definitely different
    • We must compare letters
  2. Two windows have the same fingerprint. What should we do?
    • Declare a match immediately
    • Compare the real letters to confirm
    • Ignore it
  3. What does "rolling" mean?
    • Sorting the letters
    • Updating the fingerprint by removing the leaving letter and adding the new one
    • Reversing the text