Rabin Karp Rolling Hash Pattern Match (JavaScript)
Find all occurrences of a pattern in text using the Rabin Karp algorithm with a rolling hash for O(n+m) average time complexity.
Code
function rabinKarp(text, pattern) {
const base = 256, mod = 101;
const n = text.length, m = pattern.length;
if (m === 0 || m > n) return [];
let patHash = 0, txtHash = 0, h = 1;
for (let i = 0; i < m - 1; i++) h = (h * base) % mod;
for (let i = 0; i < m; i++) {
patHash = (patHash * base + pattern.charCodeAt(i)) % mod;
txtHash = (txtHash * base + text.charCodeAt(i)) % mod;
}
const result = [];
for (let i = 0; i <= n - m; i++) {
if (patHash === txtHash && text.slice(i, i + m) === pattern) result.push(i);
if (i < n - m) {
txtHash = (base * (txtHash - text.charCodeAt(i) * h) + text.charCodeAt(i + m)) % mod;
if (txtHash < 0) txtHash += mod;
}
}
return result;
}How it works
Count the function rabinKarp as the entire surface area of Rabin Karp Rolling Hash Pattern Match (JavaScript).
The core work runs in nested loops — outer for (let i = 0; i < m - 1; i++) h = (h * base) % mod;, inner for (let i = 0; i < m; i++).
The result is a fresh construction, so callers can keep their originals.
Points of care
- The guard
m === 0 || m > nshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature is function rabinKarp(text, pattern)
Core lines
if (m === 0 || m > n) return [];
if (txtHash < 0) txtHash += mod;
Interactive Tools for This Topic
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Does `rabinKarp` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `rabinKarp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.