Rabin–Karp string search: Examples & Code

Algorithm Visualizations November 16, 2026 javascript

Published by Dimitris Kougioumtzis · Updated

Search with a rolling hash, verifying characters when hashes match.

Roll a hash across windows, verifying actual characters when hashes agree so collisions cannot create false matches.

Open the 3D visualization

Rabin–Karp string search example state preview
Preview of the example's final state. Complete values are available in the worked example and interactive timeline.

When to use Rabin–Karp string search

Learning rolling hashes and exact matching.

Choosing an alternative

KMP gives a deterministic linear bound without hashes.

Worked example: input and state changes

Example input

ABABABCABAB | ABABC

These checkpoints follow the actual example timeline. State details show the stored values and decisions; use the visualization to inspect every intervening step.

  1. Step 0: Initial state.

    State at this checkpoint
    {
      "values": [
        "A",
        "B",
        "A",
        "B",
        "A",
        "B",
        "C",
        "A",
        "B",
        "A",
        "B"
      ],
      "active": []
    }
  2. Step 3: Window 2: text hash 98, pattern hash 98.

    State at this checkpoint
    {
      "values": [
        "A",
        "B",
        "A",
        "B",
        "A",
        "B",
        "C",
        "A",
        "B",
        "A",
        "B"
      ],
      "active": [
        2
      ]
    }
  3. Step 7: Hash matches: verify actual characters.

    State at this checkpoint
    {
      "values": [
        "A",
        "B",
        "A",
        "B",
        "A",
        "B",
        "C",
        "A",
        "B",
        "A",
        "B"
      ],
      "active": [
        5
      ]
    }
  4. Step 10: Window 4: text hash 69, pattern hash 98.

    State at this checkpoint
    {
      "values": [
        "A",
        "B",
        "A",
        "B",
        "A",
        "B",
        "C",
        "A",
        "B",
        "A",
        "B"
      ],
      "active": [
        4
      ]
    }
  5. Step 13: Matches at indices: 2.

    State at this checkpoint
    {
      "values": [
        "A",
        "B",
        "A",
        "B",
        "A",
        "B",
        "C",
        "A",
        "B",
        "A",
        "B"
      ],
      "active": []
    }

Expected final state

Matches at indices: 2.

Complexity and input bounds

Family: Strings. Time complexity: O(nm) worst; O(n + m) expected.

Space complexity: O(1) rolling state, excluding match output.

Working-space bounds describe algorithm state and any explicitly noted output, excluding the visualization's saved timeline. Recording frames can use more memory than running the function alone. Here n is sequence length, V and E are vertex and edge counts, and other parameters refer to the named input dimensions.

Text | pattern. Use 1–40 letters for text and 1–16 for pattern.

The playground validates these limits before starting. Downloaded functions are callable implementations, with parameter and output-buffer contracts in their comments; they do not all repeat the playground's input validation.

Common mistakes and limitations

Hash equality is not string equality; verification is mandatory and worst-case work can remain quadratic.

Further reading

For background on algorithm analysis and the JavaScript function interface:

Editorial and testing approach · Browse all algorithm guides

Complete JavaScript implementation

javascript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// ASCII letter-code arrays, n ≤ 40, 1 ≤ m ≤ 16. Hash matches are verified to avoid false positives. Writes all overlapping matches and returns count. Reference snippets assume validated playground inputs. Fixed scratch buffers have 256 slots. Sorting variants may use a different traversal strategy than the animation.
function algorithm(text, n, pattern, m, matches) {
    if (m > n) { return 0; }
    let high = 1; let ph = 0; let hash = 0; let count = 0;
    for (let i = 1; i < m; i++) { high = high * 31 % 101; }
    for (let i = 0; i < m; i++) { ph = (ph * 31 + pattern[i]) % 101; hash = (hash * 31 + text[i]) % 101; }
    for (let i = 0; i <= n - m; i++) {
        if (hash == ph) {
            let j = 0; while (j < m && text[i + j] == pattern[j]) { j++; }
            if (j == m) { matches[count++] = i; }
        }
        if (i < n - m) {
            hash = (hash - text[i] * high) % 101; if (hash < 0) { hash += 101; }
            hash = (hash * 31 + text[i + m]) % 101;
        }
    }
    return count;
}

Source

Primary research source for the algorithm or its underlying method. The playground is a bounded teaching implementation, not the publication's original program.