Skip to the workspace
Pebellslearn by building
String Algorithms  ›  Lesson

Rabin-Karp & Rolling Hashes

Rolling Hashing 30 minFingerprint every window in O(1) and compare characters only on a hit

dsa / Rabin-Karp & Rolling Hashes

Explore each scene at your own pace.

01 · The naive search, and where it wastes work

The naive search, and where it wastes work

Rabin-Karp & Rolling Hashes

Definition
Rabin-Karp searches for a pattern in a text by comparing hash values, which are numbers computed from the characters in a window. A rolling hash updates that number in O(1) as the window slides, and each hash match is checked against the real characters.
In plain words
Give each stretch of text a fingerprint and compare fingerprints, which is quick, instead of comparing letter by letter. Sliding along by one letter only needs a small tweak to the fingerprint. Matching fingerprints are still checked, since two different words can share one.

In short: Rabin-Karp fingerprints every window with a polynomial hash, so comparing two windows is one number comparison instead of m character comparisons. Sliding the window removes the leaving character's weight, shifts, and adds the entering character, all in O(1), so the whole scan is O(n + m) expected. A hash match is only a hint — two different windows can collide — so every hit must be verified against the real characters before it counts as a match.

A window "41" sliding to "18": drop the leaving 4's weight, shift, add the entering 8

From here on, the course builds Quarry, a small search-and-storage engine: the kind of program that sits under a log viewer, a code-search box or a document store. Each section adds one subsystem, and this one adds the text index. A user types a phrase, and Quarry says where it occurs in a pile of text without reading any character more often than it has to.

The first question is the obvious one. How do you find a pattern of length m inside a text of length n?

The naive search, and where it wastes work

Line the pattern up at every start position and compare character by character until something differs:

python

On ordinary English the inner loop usually stops at the first character, so the search is close to O(n). On repetitive text it is not. A thousand as and a pattern of twenty as then a b make every alignment compare 21 characters before failing, which is about n · m comparisons. Machine logs, DNA and padded records are exactly that kind of repetitive.

What does this print?
text, pattern = "aaaaa", "aab"
compares = 0
for i in range(len(text) - len(pattern) + 1):
    for j in range(len(pattern)):
        compares += 1
        if text[i + j] != pattern[j]:
            break
print(compares)
Scene 1 of 12
Project context and further resources
You're building a piece ofQuarry — the text index
This piece — hash_scan(): Rolls a hash across the text and reads characters only where a fingerprint matches.
Scenario A user searches Quarry's server log for "timeout". The scanner fingerprints each 7-character window as it slides past, and it only reads characters where a fingerprint matches.
hash_scan.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
hash_scan(text, pattern, mod) → dictEvery real match of the pattern, plus how many hash hits turned out to be false alarms.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.