Rabin–Karp substring search
You want to find CD in ABCDAB. Rabin–Karp gives the pattern and each window of text a numerical fingerprint called a hash. When the window moves one place to the right, the next hash comes from the previous one. Only windows with a matching hash need a character-by-character check.
Video walkthrough
A number for each window
A window contains as many characters as the pattern. Give each character a number. In the example A = 1, B = 2, C = 3 and D = 4. With base 10, AB gives 1 × 10 + 2 = 12. CD gives 3 × 10 + 4 = 34. We keep the remainder after division by 13, so the two hashes are 12 and 8.
To build a hash, start at zero. For each character, multiply the current value by the base, add the character’s number and keep the remainder. Modulo 13 is small enough to make collisions easy to see in the player.
Remove, shift, add
Move the first window from AB to BC. Remove the leading A by subtracting its contribution, 1 × 10, from 12. That leaves 2. Multiply by 10 to move B into the leading place. Add 3 for the incoming C. The remainder of 23 modulo 13 is 10, the new window hash.
For a window of length m, the leading place has weight 10^(m − 1). Compute its remainder a single time and reuse it for every outgoing character. If subtraction yields a negative value, take the equivalent non-negative remainder. For example, −5 becomes 8 modulo 13.
Taking the remainder after each operation preserves the hash. The updated value is the same as if we hashed the whole new window from scratch.
When two hashes match
A collision occurs when different strings give the same hash. Try BDAA with pattern AA. The values for BD and AA before taking the remainder are 24 and 11. Both give hash 11. Comparing B with A rejects BD. The final window AA passes both character checks and gives a match at position 3.
The player counts hash comparisons, direct character comparisons and rejected collisions separately. All match positions start at 1, and searching continues after a match so overlapping occurrences can be found.
JavaScript implementation
The implementation maps A–Z to 1–26 and other characters to their Unicode code point plus 27. It returns every match position and the same three counters as the player. Array.from splits strings into Unicode code points.
With n text characters and m pattern characters, preparing the first two hashes takes O(m). Updating and comparing the hashes over all windows takes O(n) overall. Each matching hash can require up to m character comparisons, so the worst case is O(nm). The rolling calculation uses constant extra space. The code also allocates O(n + m) for character arrays, plus space for the matches. The player keeps step history to support seeking.
Show executable code
function rabinKarpSearch(text, pattern) {
const source = Array.from(text);
const target = Array.from(pattern);
const m = target.length;
if (m === 0) throw new RangeError("The pattern must not be empty");
const base = 10;
const modulus = 13;
const mod = value => ((value % modulus) + modulus) % modulus;
const code = symbol => {
const point = symbol.codePointAt(0);
return point >= 65 && point <= 90 ? point - 64 : point + 27;
};
const hash = symbols => {
let value = 0;
for (let j = 0; j < m; j++) value = mod(value * base + code(symbols[j]));
return value;
};
const result = { positions: [], hashChecks: 0, symbolChecks: 0, collisions: 0 };
if (m > source.length) return result;
let weight = 1;
for (let j = 1; j < m; j++) weight = mod(weight * base);
const patternHash = hash(target);
let windowHash = hash(source);
const last = source.length - m;
for (let start = 0; start <= last; start++) {
result.hashChecks++;
if (windowHash === patternHash) {
let j = 0;
while (j < m) {
result.symbolChecks++;
if (source[start + j] !== target[j]) break;
j++;
}
if (j === m) result.positions.push(start + 1);
else result.collisions++;
}
if (start < last) {
const remaining = mod(windowHash - code(source[start]) * weight);
windowHash = mod(remaining * base + code(source[start + m]));
}
}
return result;
}Further reading
R. M. Karp and M. O. Rabin — Efficient Randomized Pattern-Matching Algorithms