Rabin-Karp finds a pattern of length m in a text of length n by comparing hashes instead of strings. Hash the pattern once. Hash the first window of m characters, then slide: the next window's hash is computed in O(1) from the current one by subtracting the leaving character times BASE^(m-1), multiplying by BASE, and adding the entering character, all modulo a large prime. That is the rolling hash. When a window's hash equals the pattern's, compare the actual characters, because different strings can share a hash. Expected time is O(n + m); the worst case is O(n·m) if nearly every window collides or matches. In JavaScript, keep every intermediate product below 2^53 (or use BigInt), and add the modulus back after the subtraction so the hash never goes negative.
Rabin-Karp string-matching DSA problem (recurring at Microsoft).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The hash treats a window as a number in base 256, reduced modulo a prime. high is the weight of the window's first character, needed to remove it. After the subtraction the value can be negative, and % in JavaScript keeps the sign of the left side, so the modulus is added back before the second %. With base 256, modulus about 10⁹ and UTF-16 code units up to 65,535, the largest product is about 6.6 × 10¹³, safely below 2⁵³. A hash hit is confirmed with startsWith at that position.
// Give every window of the text a number (a hash) and compare numbers instead of strings.// The trick is the rolling hash: the next window's hash comes from the current one in O(1),// by removing the character that leaves and adding the one that enters.function search(text, pattern) {const n = text.length;const m = pattern.length;if (m === 0) return 0;if (m > n) return -1;const BASE = 256;const MOD = 1000000007; // a prime; every product below stays under 2^53let high = 1; // BASE^(m - 1) % MOD: the weight of a window's first characterfor (let i = 1; i < m; i++) high = (high * BASE) % MOD;let want = 0;let have = 0;for (let i = 0; i < m; i++) {want = (want * BASE + pattern.charCodeAt(i)) % MOD;have = (have * BASE + text.charCodeAt(i)) % MOD;}for (let i = 0; ; i++) {// Equal hashes only say "probably": two different strings can share one. Compare for real.if (have === want && text.startsWith(pattern, i)) return i;if (i + m >= n) return -1;have = (((have - text.charCodeAt(i) * high) % MOD) + MOD) % MOD;have = (have * BASE + text.charCodeAt(i + m)) % MOD;}}
passes 7 checks run on every build, against the native method where there is one
- finds the first match
- at the start, at the very end, and not at all
- repeated characters
- an empty pattern, a longer pattern, an empty text
- characters beyond one byte
- agrees with indexOf on every window of a text
- a long text of one letter stays exact
The loop now visits every window and collects each confirmed position, so overlapping matches such as aba in abababa are all found. Making the modulus a parameter lets a check force collisions: with a modulus of 3, about a third of all windows share the pattern's hash, stats.compared shows those extra comparisons, and the result is unchanged. With the real modulus the same text needs only the three true comparisons.
// Every match, overlapping ones included. The modulus is a parameter so a check can make it// tiny on purpose: then many windows share the pattern's hash, and the real comparison is what// keeps the answer right. `stats.compared` counts those comparisons.function searchAll(text, pattern, { mod = 1000000007, stats } = {}) {const n = text.length;const m = pattern.length;const found = [];if (m === 0 || m > n) return found;const BASE = 256;let high = 1;for (let i = 1; i < m; i++) high = (high * BASE) % mod;let want = 0;let have = 0;for (let i = 0; i < m; i++) {want = (want * BASE + pattern.charCodeAt(i)) % mod;have = (have * BASE + text.charCodeAt(i)) % mod;}for (let i = 0; i + m <= n; i++) {if (have === want) {if (stats) stats.compared = (stats.compared ?? 0) + 1;if (text.startsWith(pattern, i)) found.push(i);}if (i + m < n) {have = (((have - text.charCodeAt(i) * high) % mod) + mod) % mod;have = (have * BASE + text.charCodeAt(i + m)) % mod;}}return found;}
passes 7 checks run on every build, against the native method where there is one
- every match, overlapping ones too
- the first and the last window
- no match, an empty pattern, a longer pattern
- agrees with indexOf
- with a tiny modulus hashes collide, and the answer is still right
- with the real modulus only true matches are compared
- many matches in a long text
For a single pattern, indexOf or Knuth-Morris-Pratt is at least as good. Rabin-Karp's advantage is a set of patterns: store each pattern's hash in a Map, and each window needs one lookup, however many patterns there are. Patterns are grouped by length because a window has one length; each group is one pass over the text. Patterns that happen to share a hash sit in the same bucket and are told apart by the real comparison.
// Where Rabin-Karp beats the other string searches: many patterns at once. Patterns of one// length share a single pass over the text; a window's hash is looked up in a table of the// pattern hashes, so the cost per window does not grow with the number of patterns.function searchMany(text, patterns) {const BASE = 256;const MOD = 1000000007;const hashOf = (s, length) => {let h = 0;for (let i = 0; i < length; i++) h = (h * BASE + s.charCodeAt(i)) % MOD;return h;};const found = new Map(patterns.map((p) => [p, []]));const byLength = new Map(); // length → (hash → patterns with that hash)for (const p of found.keys()) {if (p.length === 0 || p.length > text.length) continue;if (!byLength.has(p.length)) byLength.set(p.length, new Map());const table = byLength.get(p.length);const h = hashOf(p, p.length);if (!table.has(h)) table.set(h, []);table.get(h).push(p);}for (const [m, table] of byLength) {let high = 1;for (let i = 1; i < m; i++) high = (high * BASE) % MOD;let have = hashOf(text, m);for (let i = 0; i + m <= text.length; i++) {for (const p of table.get(have) ?? []) {if (text.startsWith(p, i)) found.get(p).push(i);}if (i + m < text.length) {have = (((have - text.charCodeAt(i) * high) % MOD) + MOD) % MOD;have = (have * BASE + text.charCodeAt(i + m)) % MOD;}}}return Object.fromEntries(found);}
passes 7 checks run on every build, against the native method where there is one
- several patterns, each with all its positions
- a pattern that is missing, empty or too long gets an empty list
- a pattern listed twice is reported once
- overlapping matches and patterns inside patterns
- agrees with indexOf for every pattern
- no patterns, and an empty text
- two hundred patterns of one length over a long text
Plagiarism and duplicate detection
Finding passages shared between documents is a search for many patterns at once: hash every k-word window of one document and look the hashes up in the other. Rabin-Karp's rolling hash is the standard way to produce those window hashes cheaply.
Content-defined chunking
Backup and sync tools cut files into chunks where a rolling hash of the last few bytes hits a chosen value, so an insertion early in a file doesn't shift every later chunk boundary.
Numbers above 2^53
JavaScript numbers are doubles: integers are exact only up to Number.MAX_SAFE_INTEGER (2⁵³ − 1). A hash that multiplies two large values must keep the product under that, or use BigInt.
Returning a match on equal hashes without comparing the characters.
Letting the hash go negative after the subtraction:
%keeps the sign of the dividend in JavaScript.Overflowing 2^53 by picking a modulus or base so large that the products lose precision.
Recomputing each window's hash from scratch, which is O(n·m) and misses the point of the algorithm.
Forgetting the last window, or reading one character past the end when rolling.
Claiming O(n + m) as the worst case: that is the expected time; the worst case is O(n·m).
Why a prime modulus?
A prime that shares no factor with the base spreads the hash values evenly over the range, so unrelated windows rarely collide. A modulus that divides a power of the base would make the hash depend on only the last few characters.
What is the worst case, and when does it happen?
O(n·m): when every window is compared in full. That happens with real matches everywhere (aaa in a text of only a) or with an adversarial input built to collide with a known modulus. Choosing the modulus at random, or using two independent hashes, makes forced collisions impractical.
When would you pick KMP instead?
For one pattern when you need a guaranteed O(n + m) worst case and no hashing: KMP never re-reads a text character. Rabin-Karp wins for many patterns at once and for two-dimensional or substring-similarity problems.
Does it work with emoji and other characters outside the basic plane?
Yes. It hashes UTF-16 code units, the same units length, charCodeAt and indexOf use, so positions agree with indexOf. A character made of two code units is just two units to the hash.
- en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith