Rabin-Karp
Compare a rolling hash of each window with the pattern hash and read characters only on a hash hit.
String Matching: Rabin-Karp rolling hash
Shift 0, window "abra" hashes to 57. Equal to the pattern hash 57, and the characters agree: a match at index 0.
Cost
- Best
- O(n + m)
- Average
- O(n + m)
- Worst
- O(n * m)
- Space
- O(1)
Worst case from hash collisions. Expected linear.
Related
Taught by the same lesson
String Matching covers these too, in the same run.