Imagine you need to find the word "needle" inside a document that is millions of characters long. The simplest approach — check every position, compare the pattern character by character — works, but it can examine each character of the text m times (once for each of the m characters in the pattern), giving work in the worst case.
Michael Rabin and Richard Karp published a better idea in 1987: instead of comparing characters directly, compute a fingerprint (a hash) of the pattern and slide a matching-size window across the text. At each position you compare two integers rather than up to m characters. The trick is making the window slide in per step — by updating the hash algebraically rather than recomputing it from scratch.
The resulting algorithm finds any pattern in time on average, and it extends naturally to searching for multiple patterns at once — something that beats even the Knuth-Morris-Pratt automaton at scale. It is one of the cleanest examples in computer science of turning a comparison problem into an arithmetic one.
Comments
Loading comments...