Rolling hashes and Rabin-Karp
1 Comparing letters at every start is slow
We want every index where a pattern appears in a text. The plain way tries every start and compares the pattern letter by letter. Most starts fail at the first letter, so this looks cheap.
Some inputs break it. Take a text of 10⁵ copies of a, and a pattern of 9,999 copies of a followed by a b. At every start, 9,999 letters match before the b fails. That is around 10⁹ comparisons. At about 10⁸ steps a second, it gets Time Limit Exceeded (TLE).
Comparing two numbers takes one step. So we turn each window of the text, the m letters from one start, into a number, and compare it with the pattern's number. That number must be cheap to get, and it must fit in a variable.
2 A word read as a number
We read a word the way we read the digits of a number. For now, our letters go only up to i, and each letter is one digit: a = 1, b = 2, up to i = 9. Then cab is the number 312:
The first letter carries the most weight, as the hundreds digit does. Two different words of the same length differ in some digit, so equal numbers mean equal words.
We build the number from left to right. We multiply what we have by 10, then add the next letter. For cab, that goes 3, then 31, then 312. This number is the word's hash, and 10 is the base, B.
Real text has 26 letters, so the base must be larger than 26. Otherwise a letter's value would carry into the next place. Code usually takes B = 31 for lowercase letters, the multiplier from the hash map lesson. A window with letter values s₀ to sm−1 has the hash
3 Rolling the window one letter
Our running example looks for the pattern cab in a text of 9 letters:
Building each window's number from scratch costs m steps. That brings back the n × m. The sliding window lesson had the fix. When the window moves one place, one letter leaves, one comes in, and the letters in between stay. The digits show what that does to the number:
The leaving letter sat in the highest place, worth Bm−1. We calculate that weight once, as high. Then each move is one line:
| start | window | hash |
|---|---|---|
| 0 | cab | 312 |
| 1 | abh | 128 |
| 2 | bhi | 289 |
| 3 | hid | 894 |
| 4 | idc | 943 |
| 5 | dca | 431 |
| 6 | cab | 312 |
Each row costs a few steps, however long the window is. The windows at starts 0 and 6 have the pattern's number, 312. Those are the two matches.
4 Keeping the number small
A pattern of 10⁴ letters gives a number with 10⁴ digits, and no variable holds that. So we keep only the remainder after dividing by a large prime M. The fast power lesson showed that addition and multiplication give the same remainder whether we take % M after every step or once at the end. So each move takes % M.
The code uses M = 10⁹ + 7. The trace keeps B = 10 and uses a tiny M = 97, so the numbers stay short. Then high is 100 % 97 = 3. Each row takes three steps, with the names from the code below:
removed= leaving × 3.- after =
textHash−removed. - next = (after × 10 + entering) % 97.
In row 0, c leaves and h enters: 3 × 3 = 9, then 21 − 9 = 12, then (12 × 10 + 8) % 97 = 31.
| start | window | hash | removed | after | next |
|---|---|---|---|---|---|
| 0 | cab | 21 | 9 | 12 | 31 |
| 1 | abh | 31 | 3 | 28 | 95 |
| 2 | bhi | 95 | 6 | 89 | 21 |
| 3 | hid | 21 | 24 | −3→94 | 70 |
| 4 | idc | 70 | 27 | 43 | 43 |
| 5 | dca | 43 | 12 | 31 | 21 |
| 6 | cab | 21 |
Each hash is the remainder of that window's number from section 3, such as 312 % 97 = 21, yet the roll never held the big numbers.
Row 3 dips below zero: 21 − 24 = −3. In most languages, % of a negative number stays negative, and the hash would never equal 21 again. As in the fast power lesson, we add M before the %, so −3 becomes 94.
5 Equal hashes, then check the letters
The pattern's hash is 312 % 97 = 21. The trace finds 21 at starts 0, 3 and 6. But start 3 holds hid. Its number 894 is 312 + 6 × 97, so both leave the remainder 21.
Two different windows with the same hash are a collision. There are far more words than remainders, so some words must share one, as keys share buckets in a hash map.
So Rabin-Karp uses the hash as a quick filter. A different hash proves the window is not the pattern. An equal hash only means "maybe", so we compare the letters. Start 3 fails that check, and the answer is [0, 6].
C++
Use long long. textHash * BASE reaches about 3 × 10¹⁰, past the 2 × 10⁹ an int holds. % keeps the minus sign, so the + MOD is needed.
Use long. textHash * BASE reaches about 3 × 10¹⁰, past the 2 × 10⁹ an int holds. % keeps the minus sign, so the + MOD is needed.
No overflow and no minus sign. Integers grow as needed, and % never returns a negative number here, so the line after removed needs no + MOD. pow(BASE, m - 1, MOD) calculates high with the modulus built in.
Numbers are exact up to about 9 × 10¹⁵. The largest product here is about 3 × 10¹⁰, so it is safe. % keeps the minus sign, so the + MOD is needed. Prefix hashes, in section 7, multiply two hashes, about 10¹⁸. That is past the exact range, so they need BigInt.
int is 64 bits on today's machines, so textHash*base, about 3 × 10¹⁰, fits. % keeps the minus sign, so the + mod is needed.
Use i64. text_hash * BASE reaches about 3 × 10¹⁰, past what an i32 holds. % keeps the minus sign, so the + MOD is needed. The strings are compared as bytes, which is safe for plain letters.
Use long. textHash * BASE reaches about 3 × 10¹⁰, past the 2 × 10⁹ an int holds. % keeps the minus sign, so the + MOD is needed.
Every tab returns [0, 6] for cab in cabhidcab. For aba in abacabababa, it returns [0, 4, 6, 8], where the matches overlap.
Cost. Hashing the pattern and the first window takes O(m), and each of the n − m moves takes O(1). Each equal hash adds up to m steps for the check. On ordinary text, matches are few, so the total is O(n + m) time, and O(1) space besides the answer.
Many matches make the check costly. Take a text of 10⁵ copies of a and a pattern of 5 × 10⁴ copies. Every one of the 5 × 10⁴ starts matches, and each check reads 5 × 10⁴ letters. That is around 2.5 × 10⁹ steps, and TLE.
6 How often hashes collide
With M = 10⁹ + 7, two different windows share a hash about once in 10⁹ tries. Whether that is safe depends on the number of tries:
- One pattern against every window. A text of 10⁶ letters makes about 10⁶ tries. A collision turns up in about one run in 1,000, and the check catches it.
- Every window against every other. Some problems keep all the window hashes in a set to find a repeat. Then every pair is a try. 10⁵ windows make about 5 × 10⁹ pairs, so we expect around 5 collisions.
The second case is the birthday effect. In a room of 23 people, two share a birthday more often than not, though a year has 365 days. Collisions become likely at about √M hashes, around 3 × 10⁴ here. Inputs can also collide on purpose: with B = 31, edqmlbzosj and coozitkknv share a hash.
Double hashing fixes this. Each window keeps two hashes, with different bases and primes, such as 31 with 10⁹ + 7 and 37 with 998,244,353. Two windows collide only when both agree, about once in 10¹⁸ tries. Over 5 × 10⁹ pairs, that is around 1 in 10⁸. So we can trust a matching pair without the letter check, and even the all-a text runs in O(n + m).
7 Any substring's hash: prefix hashes
Rabin-Karp slides one window along. Some problems compare pieces from anywhere in the string. Prefix hashes give any piece's hash in O(1), much as prefix sums give any range sum.
h[i] is the hash of the first i letters, built as in section 2. h[0] is 0, and h[i + 1] = h[i] * B + s[i]. With B = 10 and no modulus, our text gives 0, 3, 31, 312, 3128, 31289, 312894, and so on. To get hid, at indexes 3 to 5:
Prefix sums only subtracted. Here, inside h[6], the three letters after cab pushed it three places to the left. So we shift h[3] three places too before we subtract. For the piece that starts at index l and ends just before r:
With a modulus, we keep the powers of B in an array pw, and add M after the subtraction:
h[0] = 0, pw[0] = 1
for i from 0 to n - 1:
h[i + 1] = (h[i] * B + value(s[i])) % M
pw[i + 1] = pw[i] * B % M
hash(l, r) = (h[r] - h[l] * pw[r - l] % M + M) % M
Building both arrays takes O(n) time and space. Then each piece's hash takes O(1), so two pieces of any length compare in O(1), with a double hash or a letter check.
8 Mistakes and edge cases
- Overflow before the
%.textHash * BASEreaches about 3 × 10¹⁰, andh[l] * pw[r - l]about 10¹⁸. A 32-bitintholds about 2 × 10⁹, so both need 64-bit numbers, with the%right after each product. - Giving a the value 0. Then a, aa and aaa all hash to 0, as leading zeros vanish from a number. Pieces of different lengths collide, for example in a set of distinct substrings. The value
c - 'a' + 1starts at 1. - No letter check with one hash. With M = 97, our search also reports hid and returns [0, 3, 6].
- A modulus that is too small. M = 97 cannot tell 98 windows apart. Even 10⁹ + 7 is too small for a set of 10⁵ hashes, so use two primes there.
- Negative remainders. Without the + M, row 3 of the trace leaves −3. At start 6 the hash is −76 instead of 21, and the search returns [0] instead of [0, 6].
9 When to use a rolling hash
The sign is a problem that compares pieces of a string many times, where comparing letters each time is too slow:
- Find a pattern. Rabin-Karp, as above. KMP and the Z-function, the two lessons before this one, are also O(n + m) and never collide. Hashing fits the other shapes better.
- A repeated piece of fixed length. Slide a window and keep each hash in a set. A hash already there is a repeat. Repeated DNA Sequences uses windows of 10 letters.
- The longest repeated piece. If a piece of length L appears twice, so does a piece of every shorter length. So we binary search on L, with the set as the check. This is Longest Duplicate Substring, in O(n log n).
- A prefix against a suffix. With prefix hashes, a prefix and a suffix of the same length compare in O(1).
- Palindromes. A piece is a palindrome when its forward hash equals its backward hash.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.