Rabin–Karp algorithm
How to find a pattern in a text by comparing one small number per position instead of whole strings, worked through on ten digits.
In 30 seconds
Rabin–Karp searches a text for a pattern by comparing hashes: small numbers computed from strings. It hashes the pattern once, then hashes each window of the text and compares the two numbers.
The trick is the rolling hash. Sliding the window one place updates the hash with a few operations instead of recomputing it.
Different strings can share a hash, so every hash match is confirmed character by character. Because one lookup can test a window against a whole set of hashes, the method is good at searching for many patterns at once.
Rabin–Karp algorithm, step by step
Real code keeps only the remainder at every step and uses a large prime modulus. Expected time is linear in the text length; the rare worst case, with constant false positives, is as slow as the naive search.
- Step 1: The slow way. To find 926 in the text, the obvious method lines the pattern up at every position and compares character by character. For long patterns and long texts, that is a great many comparisons, most of them wasted.
- Step 2: Give the pattern a hash. A hash squeezes a string into one small number. Here we read the three digits as a number and keep the remainder after dividing by 13. Equal strings always get equal hashes, so comparing two numbers can stand in for comparing two strings.
- Step 3: Hash the first window. Take the first three characters of the text, the window, and hash them the same way. The hashes differ, so the window cannot be the pattern. One number comparison rules it out; no characters are compared.
- Step 4: Roll the hash. Slide the window one place. Instead of hashing three characters from scratch, update the old value: remove the digit that left, shift, add the digit that entered. This rolling hash costs the same few operations whether the window is 3 characters or 3,000.
- Step 5: A false positive. Two more slides, then window 159 hashes to 3, the same as the pattern. Only now are characters compared, and the first pair already differs. With just 13 possible hashes, different strings must sometimes share one. A match of hashes is a hint, never proof.
- Step 6: A real match. Window 592 hashes to 7 and is skipped. The next window hashes to 3, and this time every character agrees: the pattern starts at index 5. Six windows were tested with one number comparison each, and characters were compared for only two of them.
- Step 7: Many patterns, one pass. Looking for several patterns of the same length costs almost nothing extra. Put all their hashes in a set, then roll through the text once and look each window hash up in the set. Plagiarism detectors use this to search for thousands of phrases at once. Real code also uses a huge modulus, so false positives are rare.
Try it yourself
Learn this first
Spotted a mistake on this page?