Rabin–Karp algorithm
0 1 2 3 4 5 6 7 8 9
1 5 2 6 1 5 2 6 1 5
Naïve String-Matching Algorithm
Compare the pattern 𝑃 with every possible substring of text 𝑇 character by character
Feature Naïve String Matching Rabin–Karp Algorithm
Idea Check pattern at every Use hashing to compare pattern with
position directly text windows
Working Compare characters one by Compare hash values first, then
one verify
Efficiency Repeats comparisons Avoids unnecessary comparisons
using hash
Worst Case O(n·m) O(n·m) (due to collisions)
Space O(1) O(1)
Complexity
Use Case Simple implementation Multiple pattern matching,
plagiarism detection
Collision Issue No Yes (hash collision possible)
KMP (Knuth–Morris–Pratt) is a string matching algorithm used to find occurrences of
a pattern (P) in a text (T) efficiently
n = length of text
m = length of pattern
TC= O(m+n)
SC=O(m)