Skip to content
Efficient

Rabin-Karp Algorithm

Pattern matching using rolling hashes.

Time Complexity
O(N + M)
Space Complexity
O(1)

Interactive Visualization

Playback Speed
Execution State
STEP 1 / 15
Text
A
0
B
1
A
2
B
3
C
4
A
5
B
6
A
7
B
8
D
9
Pattern
A
0
B
1
A
2
B
3
D
4
Pattern Hash
63
Sliding Hash
62
Process Description

Initial hashes computed. Pattern hash: 63, Text window hash: 62

Technical Guide

Rabin-Karp uses Hashing to find patterns. Instead of comparing characters, it computes a hash of the pattern and compares it to the hashes of all windows in the text. If hashes match, it performs a final character check (to handle collisions). This is exceptionally powerful for searching for multiple patterns at once.

Logical Phases

  • 1
    Computing the hash of the pattern in O(M).
  • 2
    Computing the initial hash of the first text window.
  • 3
    Sliding the window and updating the hash in O(1) using math (Rolling Hash).
  • 4
    Performing character comparison only if hashes are equal.

Implementation

if (patternHash === windowHash) checkChars();

Expert Pitfalls

Poor choice of prime numbers leading to excessive hash collisions (spurious hits).