1. Hash the pattern
Build a polynomial hash of the pattern once.
patternHash = (patternHash * base + pattern.charCodeAt(i)) % modTyporithm · hard
Step 1 of 8 · intro card
String Algorithms
Slide a rolling hash over the text; on a hash match, verify the substring to rule out collisions.
Comparing the pattern at every position naively costs O(n·m).
A rolling hash updates in O(1) as the window slides: drop the leading char, add the new one.
Equal hashes only suggest a match, so a direct comparison confirms it and guards against collisions.
Rolling hash updates in O(1).
Hash equal → verify the substring.
Average O(n + m), worst O(n·m).
function rabinKarp(text, pattern) {
const n = text.length;
const m = pattern.length;
const base = 256;
const mod = 1000000007;
let patternHash = 0;
let windowHash = 0;
let power = 1;
for (let i = 0; i < m; i += 1) {
patternHash = (patternHash * base + pattern.charCodeAt(i)) % mod;
windowHash = (windowHash * base + text.charCodeAt(i)) % mod;
if (i < m - 1) power = (power * base) % mod;
}
for (let i = 0; i + m <= n; i += 1) {
if (patternHash === windowHash && text.slice(i, i + m) === pattern) {
return i;
}
if (i + m < n) {
windowHash = ((windowHash - text.charCodeAt(i) * power) % mod + mod * mod) % mod;
windowHash = (windowHash * base + text.charCodeAt(i + m)) % mod;
}
}
return -1;
}Connect each part of the code to the concept before you type.
Build a polynomial hash of the pattern once.
patternHash = (patternHash * base + pattern.charCodeAt(i)) % modPrecompute base^(m-1) to remove the leading character later.
power = (power * base) % modEqual hashes are a hint; a direct compare rules out collisions.
if (patternHash === windowHash && text.slice(i, i + m) === pattern)Subtract the outgoing character's contribution.
windowHash = ((windowHash - text.charCodeAt(i) * power) % mod + mod * mod) % modMultiply by the base and add the incoming character.
windowHash = (windowHash * base + text.charCodeAt(i + m)) % modRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText ababcabc · pattern abc · top row text, bottom row aligned pattern
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state