Rolling hash
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A rolling hash is a fingerprint of a piece of text that you can update in one step when the window slides by a letter, and that you can also get for any middle piece from prepared running values. It turns "are these two pieces equal?" into one number comparison.
Practical use cases
- Web app: Deduplicating chunks in a backup tool. A cloud backup web app splits files into chunks and wants to store identical chunks only once. A rolling hash slides through the file and cuts chunks where the fingerprint hits a pattern, so even after an insertion the later chunks match old ones and are not re-uploaded.
- Web app: Palindrome check on user text. A word-game page tests many substrings of an entered text to see if they read the same backwards. With prepared hashes, each substring check is a single comparison instead of reading letters. The checks stay quick even on long inputs, because every substring is turned into a single number once and reused.
- System: Longest repeated or common substring. Finding the longest piece shared by two texts, or counting distinct substrings, is done by comparing hashes of candidate pieces rather than the pieces themselves. This makes tasks that would need millions of string comparisons finish in a fraction of a second.
The story: Zoya's Instant Compare Trick
Zoya ran a quiz game at the school fair. Players got a long ribbon of letters and the judge kept asking: "Are the letters from slot 4 to 9 the same as the letters from slot 20 to 25?" Each question meant reading twelve letters, and with a hundred questions the queue grew long.
Zoya sat down and did homework once before the fair opened. Along the ribbon she wrote a running number under each letter: number after letter k = (number after the previous letter, shifted) + this letter. These are the prefix hashes: a hash for the first letter, the first two, the first three, and so on.
When the judge asked a question, she took the big number at the end of the piece and subtracted the part that came before it (after shifting that part to line up). The result is the hash of just that piece. Two pieces with the same hash are almost certainly the same, and each question now cost two array lookups. This is a rolling hash in its most useful form: compare any two substrings in constant time.
How to spot this problem, and where you need it
You have to compare many substrings of one or more long strings, and each direct comparison costs time proportional to the substring length.
Signs you need it
- The problem asks whether substrings are equal, repeated or palindromic, many times.
- You are building substrings in a loop just to compare them.
- Sliding window over text where the content of the window matters, not only its size.
- Memory or time blows up when you store all substrings.
Where to use it in a project
- Backup, sync and dedupe tools that find repeated chunks.
- Text analytics and word-game features that compare many substrings.
The solution
Precompute prefix hashes of the string, where each is built from the previous one with a multiplication and addition. The hash of any piece from l to r then comes from two prefix values and a power, in constant time. Compare two pieces by comparing their hashes; if they match, optionally double-check. For a sliding window, drop the leftmost letter and add the new one.
Payoff: Before: comparing substrings letter by letter, costing their length each. After: one number comparison per pair.
Explain it like I am 8
Write down a running total under a row of letters. To know the "total" of any middle piece, take the total at its right end and remove the total that came before its left end. It is like finding how much money you spent between two dates by using only your bank balance on those two dates.
How it works, step by step
- Pick a base (like 31) and a prime modulus (like 10007) so numbers never explode.
- Build
H[0] = 0andH[i+1] = (H[i] * base + letter) % modfor every letter. Also buildpw[i], the base to the power i, with the same remainder. - To get the hash of the piece
[l, r)computeH[r] - H[l] * pw[r - l], then bring it back into range with the remainder (add the modulus if negative). - Two pieces with different hashes are definitely different; with equal hashes they are probably equal.
- For safety on contests, use two different moduli or verify real letters when the answer matters.
The code in four languages
PHP
<?php
// Prefix hashes: compare any two pieces of a string in O(1).
class PrefixHash {
private array $h = [0];
private array $pw = [1];
private int $mod = 10007;
public function __construct(string $s, int $base = 31) {
for ($i = 0; $i < strlen($s); $i++) {
$this->h[] = ($this->h[$i] * $base + (ord($s[$i]) - 96)) % $this->mod;
$this->pw[] = ($this->pw[$i] * $base) % $this->mod;
}
}
// hash of s[l .. r) (r not included)
public function get(int $l, int $r): int {
$x = ($this->h[$r] - $this->h[$l] * $this->pw[$r - $l]) % $this->mod;
return ($x + $this->mod) % $this->mod; // keep it positive
}
public function same(int $a, int $b, int $len): bool {
return $this->get($a, $a + $len) === $this->get($b, $b + $len);
}
}
$ph = new PrefixHash("banana");
var_dump($ph->same(1, 3, 2)); // an vs an -> true
var_dump($ph->same(0, 2, 2)); // ba vs na -> false
var_dump($ph->same(1, 3, 3)); // ana vs ana -> trueJavaScript
// Prefix hashes: compare any two pieces of a string in O(1).
class PrefixHash {
constructor(s, base = 31) {
this.mod = 10007;
this.h = [0];
this.pw = [1];
for (let i = 0; i < s.length; i++) {
this.h.push((this.h[i] * base + (s.charCodeAt(i) - 96)) % this.mod);
this.pw.push((this.pw[i] * base) % this.mod);
}
}
// hash of s[l .. r) (r not included)
get(l, r) {
const x = (this.h[r] - this.h[l] * this.pw[r - l]) % this.mod;
return (x + this.mod) % this.mod; // keep it positive
}
same(a, b, len) {
return this.get(a, a + len) === this.get(b, b + len);
}
}
const ph = new PrefixHash("banana");
console.log(ph.same(1, 3, 2)); // an vs an -> true
console.log(ph.same(0, 2, 2)); // ba vs na -> false
console.log(ph.same(1, 3, 3)); // ana vs ana -> trueJava
import java.util.*;
public class Main {
// Prefix hashes: compare any two pieces of a string in O(1).
static class PrefixHash {
List<Integer> h = new ArrayList<>(List.of(0));
List<Integer> pw = new ArrayList<>(List.of(1));
int mod = 10007;
PrefixHash(String s, int base) {
for (int i = 0; i < s.length(); i++) {
h.add((h.get(i) * base + (s.charAt(i) - 'a' + 1)) % mod);
pw.add((pw.get(i) * base) % mod);
}
}
// hash of s[l .. r) (r not included)
int get(int l, int r) {
int x = (h.get(r) - h.get(l) * pw.get(r - l)) % mod;
return (x + mod) % mod; // keep it positive
}
boolean same(int a, int b, int len) {
return get(a, a + len) == get(b, b + len);
}
}
public static void main(String[] args) {
PrefixHash ph = new PrefixHash("banana", 31);
System.out.println(ph.same(1, 3, 2)); // an vs an -> true
System.out.println(ph.same(0, 2, 2)); // ba vs na -> false
System.out.println(ph.same(1, 3, 3)); // ana vs ana -> true
}
}Go
package main
import "fmt"
// PrefixHash lets us compare any two pieces of a string in O(1).
type PrefixHash struct {
h, pw []int
mod int
}
func NewPrefixHash(s string, base int) *PrefixHash {
p := &PrefixHash{h: []int{0}, pw: []int{1}, mod: 10007}
for i := 0; i < len(s); i++ {
p.h = append(p.h, (p.h[i]*base+int(s[i]-'a'+1))%p.mod)
p.pw = append(p.pw, (p.pw[i]*base)%p.mod)
}
return p
}
// Get returns the hash of s[l .. r) (r not included).
func (p *PrefixHash) Get(l, r int) int {
x := (p.h[r] - p.h[l]*p.pw[r-l]) % p.mod
return (x + p.mod) % p.mod // keep it positive
}
func (p *PrefixHash) Same(a, b, length int) bool {
return p.Get(a, a+length) == p.Get(b, b+length)
}
func main() {
ph := NewPrefixHash("banana", 31)
fmt.Println(ph.Same(1, 3, 2)) // an vs an -> true
fmt.Println(ph.Same(0, 2, 2)) // ba vs na -> false
fmt.Println(ph.Same(1, 3, 3)) // ana vs ana -> true
}Time: O(n) to prepare, O(1) per query · Extra space: O(n). One pass builds the tables; every substring comparison afterwards is two lookups and a bit of arithmetic.
Watch out for
- Forgetting to shift the left part by the piece length (the
pwarray), which gives wrong hashes. - Letting the subtraction go negative and not adding the modulus back.
- Treating equal hashes as a proof. It is strong evidence; use a second modulus or verify when a mistake would hurt.
Quick check
- What do we precompute so any substring hash is quick?
- A sorted list of letters
- Prefix hashes and powers of the base
- All substrings in a set
- Time to compare two substrings after preparation?
- O(length)
- O(n)
- O(1)
- Two different substrings can have the same hash. This is called...
- A rotation
- A collision
- A prefix