Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Strings & Text

The Rolling Hash.

Don't memorize Rabin-Karp — watch the hash roll. Instead of comparing characters at every position, turn each window of text into a single number and compare numbers. As the window slides, the hash updates in O(1) — drop the leaving character, add the entering one. Only when a window number equals the pattern number do you bother checking the characters.

rolling hash · fingerprint · verify · O(n + m) avg
FINGERPRINT

Hash the pattern once into a single number to compare against.

ROLLING HASH

Slide the window and update the hash in O(1), not O(m).

HASH MATCH

Equal hashes are a strong hint — but not a proof.

VERIFY

On a hash match, confirm the characters to rule out a collision.

rabin-karp.sim — find "ABC" in "ABABCABAB"
Ready

Searching for ABC (hash 28) in the text. Press Step to slide the window; each shift rolls the hash in O(1). When the window hash equals 28, verify the characters.

pattern "ABC" → hash 28
—
Window hash
0
Char checks

Compare numbers, not letters

The naive search lines the pattern up at every position and compares character by character — O(n·m) in the worst case. Rabin-Karp replaces most of those character comparisons with a single number comparison. It reads the window as a base-b number modulo a prime, so two equal windows always have equal hashes. The magic is the rolling update: sliding one step to the right does not require re-reading the window, just a subtract, a multiply, and an add.

01

Hash the pattern and first window

Compute one number for the pattern and one for the opening window, each O(m), once.

02

Compare hashes

If the window hash equals the pattern hash, it is a candidate; otherwise skip it entirely — no characters touched.

03

Roll forward

Slide by one: subtract the leaving character times bᵐ⁻¹, multiply by b, add the entering character — O(1).

04

Verify on a match

A hash match could be a collision, so confirm with a direct character check before declaring a real match.

Average time
O(n + m)
Worst case
O(n·m)
Roll per shift
O(1)
Space
O(1)

The worst case (many collisions or an adversarial input) degrades to naive speed, so for a single pattern KMP is the safer linear-time choice. Rabin-Karp wins when you search for many patterns at once — hash them all into a set and test each window hash against it — and in fingerprinting: plagiarism detection, near-duplicate finding, and content-defined chunking for deduplication all lean on rolling hashes.

Check yourself

1 · What does Rabin-Karp compare at each window?

It compares hashes first; only a hash match triggers a character-level verification.

2 · Why is the rolling hash update O(1)?

Subtract the leaving char contribution, shift the base, add the new char — constant work per slide, no re-scan.

3 · Why verify characters after a hash match?

A hash match is a strong hint, not a proof; verification rules out coincidental collisions.

The picture: one number per window

texth abracadabra735973149584573 pattern abra hashes to 73; each window below is one rolling step from the last 2 real matches, 1 collision
Text abracadabra, pattern abra, base 256, modulus 113. Under each window's first letter is the rolling hash of that window. Two highlighted windows are real matches; the marked one (raca at index 2) shares the pattern's hash by coincidence and has to be rejected by comparing characters.

Worked example, step by step

Search abracadabra for abra with base 256 and modulus 113. The pattern hash is 73. The first window is hashed once; every later one comes from the rolling update h = ((h − old·106) · 256 + new) mod 113, where 106 is 256^3 mod 113.

StartWindowHash= pattern hash?Character check
0abra73yesverified (4 chars)
1brac59noskipped
2raca73yescollision (fails at char 1)
3acad14noskipped
4cada95noskipped
5adab8noskipped
6dabr45noskipped
7abra73yesverified (4 chars)

The hash filter skipped 5 of 8 windows without reading a character. The three windows that passed cost 9 character comparisons in total; the naive scan made 16 comparisons on this tiny input. The saving is small here because the pattern is only four letters, but a window skipped costs the same one comparison whether the pattern has four characters or four thousand. The row for index 2 is the important one: raca hashes to 73, same as abra. A hash match is a hint, not a proof, which is why the verification step is not optional.

Complexity and trade-offs

CaseTimeSpaceWhy
Naive scanO(n·m)O(1)Compare the pattern at every start. Worst on text like aaaa…a with pattern aaab.
Rabin-KarpO(n + m) expected, O(n·m) worstO(1)Constant work per slide. Worst case needs many collisions, so a random base or large modulus makes it unlikely.
KMPO(n + m)O(m)Guaranteed linear for one pattern, with a failure table instead of hashing.
Boyer-Moore-HorspoolO(n/m) typical, O(n·m) worstO(σ)Skips ahead by looking at the end of the window. Often the fastest in practice for a single long pattern.
Rabin-Karp, k patterns of equal lengthO(n + k·m) expectedO(k)Put the k pattern hashes in a set and test each window once. Aho-Corasick gives the same bound with a guarantee.

For one pattern, KMP is the safer choice because its bound has no probability in it. Rabin-Karp earns its place when the hash itself is the product: searching for many patterns at once, comparing two-dimensional blocks, or fingerprinting data so that equal content is detected without storing it.

How large should the modulus be? If the hash behaves like a random function, two different windows collide with probability about 1/M; with a random base the provable bound is (m − 1)/M for windows of length m. Over a million windows that means about 8,850 false hits with M = 113, about 0.001 with M = 10⁹ + 7, and about 4 × 10⁻¹³ with M = 2⁶¹ − 1. Each false hit costs up to m character comparisons, so the O(nm) worst case needs a tiny modulus or input built to collide. Two independent moduli multiply the odds: 10⁹ + 7 and 10⁹ + 9 together give about 10⁻¹² expected false hits per million windows, at the price of two hashes per step. Once false hits are that rare, the search costs one rolling update per window plus m comparisons per true match.

Common mistakes

  • Skipping the verification step

    Reporting every hash hit as a match gives [0, 2, 7] for this search; index 2 is the raca collision. The true answer is [0, 7].

  • Letting the rolling hash go negative

    In JavaScript, C, C++ and Java the % operator keeps the sign: (-5) % 113 is -5, not 108. Run the update without adding the modulus back and the search finds [0] here instead of [0, 7], because a true match whose hash went negative never equals the pattern hash. Python's % hides the bug. Write ((h − old·p) % M + M) % M.

  • Using the wrong power in the roll

    The leaving character carries weight B^(m−1), not B^m. With the wrong power the same example reports [0], again missing real matches.

  • A modulus that is too small or a base that is fixed

    With modulus 113 there is already a collision in an eleven-letter string. Real code uses a modulus near 261 or two moduli, and a random base so an adversary cannot craft inputs that collide.

  • Relying on integer overflow instead of a modulus

    Letting a 64-bit hash wrap silently is the same as working modulo 264, with base 256 a window of 9 or more characters already overflows. That modulus is breakable with known adversarial inputs, such as Thue–Morse strings, so use a prime.

Where this shows up

  • Plagiarism and near-duplicate detection

    Systems in the MOSS family hash every k-character window of a document and keep a selected subset of the hashes (winnowing), then compare fingerprints between documents instead of full text.

  • Content-defined chunking for deduplication

    Backup tools such as restic and the Low-Bandwidth File System cut files where a rolling Rabin fingerprint over a small window hits a chosen pattern, so inserting a byte shifts only nearby chunk boundaries instead of every one after it.

  • Multi-pattern search

    Scanning text for a dictionary of same-length strings, such as known malicious snippets, is a set lookup per window with a rolling hash, then a verification only on a hit.

  • Two-dimensional matching

    Rolling the hash across rows and then down columns finds a small image or grid inside a bigger one without comparing every pixel at every offset.

SOLVE IT YOURSELF

Solve it: find a pattern with a rolling hash

Comparing the pattern against every position costs O(nm). Hash the window instead, and slide it forward in O(1) per step. Write it in Python or TypeScript, running for real in your browser.

YOUR TASK

Implement find_all(text, pattern): return every start index where pattern occurs in text. Use a rolling hash, and verify each hash match with a real comparison.

HINTS — 5 IDEAS
  1. Treat the window as a base-256 number mod a large prime: h = (h · 256 + charcode) % MOD.
  2. Rolling forward is the trick: subtract the outgoing character times 256^(m−1), multiply by 256, add the incoming one. O(1), no rehashing.
  3. Precompute 256^(m−1) mod MOD once, outside the loop.
  4. A hash match is not a match — different strings can collide. Always confirm with a direct comparison, or the algorithm is simply wrong.
  5. In TypeScript, normalise with ((x % MOD) + MOD) % MOD: the subtraction can go negative, and JavaScript’s % keeps the sign.
CPython · WebAssembly

Questions

Rabin-Karp vs KMP?

KMP guarantees O(n + m) for a single pattern by never re-reading text, using a precomputed failure table. Rabin-Karp is O(n + m) on average but can degrade with collisions; its edge is multi-pattern search and fingerprinting, where hashing many things and comparing numbers is cheaper.

Why use a prime modulus?

Taking the hash modulo a prime keeps the numbers small (they would otherwise overflow) and spreads hash values more uniformly, reducing collisions. Some implementations use two independent moduli to make collisions astronomically unlikely.

How does deduplication use rolling hashes?

Content-defined chunking rolls a hash over a file and cuts a new chunk whenever the hash hits a pattern of low bits. Identical regions across files produce identical chunk fingerprints, so storage systems store each unique chunk once.

Roll the fingerprint, verify on a hit.

Numbers beat letters when they can. Hash, roll in O(1), confirm on a match.

Finished this one? 0 / 99 Algorithms done
NextThe Non-Backtracker: KMP Next on the “Matching without backing up” ladder · rung 2 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms