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.

JavascriptData Fetching

Code

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

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.