Rabin-Karp Substring Search
The Rabin-Karp substring search algorithm is doubly clever, for it relies not on one, but two clever tricks to perform substring search in O(N) time.
The first trick is that it performs a hash function to convert the needle and haystack window into integer hash codes. That is, the entire needle becomes a single integer, and so does the haystack window. If these two integers are the same, it means that the needle and haystack window are the same.
The reason this is a big deal is that, as I noted earlier, it takes multiple steps to compare our needle to a section of the haystack. That is, comparing "aaab" to "aaaa" or "ddde” to "dddd" requires us to perform up to four comparisons. But when it comes to comparing two ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access