Rabin Karp Rolling Hash Pattern Match Typed
Find all occurrences of a pattern in text using typed Rabin Karp with a rolling hash for O(n+m) average time.
Code
function rabinKarp(text: string, pattern: string): number[] {
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: number[] = [];
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 the snippet works
Rabin Karp Rolling Hash Pattern Match Typed keeps everything in the function rabinKarp.
The structure is a loop within a loop: for (let i = 0; i < m - 1; i++) h = (h * base) % mod; outside, for (let i = 0; i < m; i++) { patHash = (patHash * base + pattern.charCodeAt(i)) % mod; txtHash =… inside.
The return value is newly constructed — inputs are never handed back.
What to watch for
- The guard
m === 0 || m > nshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads function rabinKarp(text: string, pattern: string)
Statements that matter
if (m === 0 || m > n) return [];
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. Nothing passed in is written to, which makes the call safe on shared data.
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `rabinKarp` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.