Efficient
Rabin-Karp Algorithm
Pattern matching using rolling hashes.
Time Complexity
O(N + M)
Space Complexity
O(1)
Interactive Visualization
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
- 1Computing the hash of the pattern in O(M).
- 2Computing the initial hash of the first text window.
- 3Sliding the window and updating the hash in O(1) using math (Rolling Hash).
- 4Performing 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).