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.

TypescriptData Fetching

Code

typescriptsnippet
14 lines
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 > n short-circuits the flow with an early return when 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

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.