All topics
128

Rabin-Karp: rolling-hash search

Tier 1Locked

Where it runs

1. The problem

KMP (step 127) jumps on a mismatch using a table it built from the pattern in advance. Rabin-Karp works differently. It turns each window of text (a piece as long as the pattern) into a single number and compares numbers instead of characters. Comparing two numbers takes one operation, so most positions are thrown out at once. A character-by-character check is needed only when the numbers match. The same trick carries over to searching for many patterns of one length at once and to finding a small picture inside a big one. That is where it pays off most.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Problems that compare many substrings of the same length, such as finding repeats or the longest repeated piece. A rolling hash updates each window in O(1), and a real comparison runs only when two hashes match.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy