The Rabin-Karp algorithm is a string-searching algorithm that uses hashing to find patterns in strings. A string is an abstract data type that consists of a sequence of characters. Letters, words, sentences, and more can be represented as strings.
String matching is a very important application of computer science. If you’ve ever searched through a document for a particular word, then you have benefitted from string-matching technology. String matching can also be used to detect plagiarism by comparing strings in document with strings in document .
Here are examples of strings in Python:
1 2 3
Say there is a word of length and a document of length . Both the word and the document are represented as strings. The naive way to search the document for the word would be to start at the beginning of the document and check every sequential letters to see if it matches up with the letters in the word. If the letter slice of the document matches with the letters in the word, then a match has been found. This is a brute-force method of string checking, and after it has run, it will certainly output the correct answer (whether the word is in the document or not). However, this algorithm takes time, in its worst case, to complete since for nearly every position in the document, the algorithm performs comparisons to check if there is a match. If is very large and , then the algorithm takes time to complete. This is very slow.
Say you want to search a DNA sequence for a particular sequence of three bases, ATA. Below is an animation depicting this search using the naive string-matching algorithm.
Here is a Python implementation of the brute-force string-searching algorithm described above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Imagine searching a string of a billion “ACC” segments followed by a single “ATA” segment. To search this string for “ATA” would result in the worst-case running time of .
One way to make this brute-force algorithm a bit smarter and more efficient is to reduce the number of needless comparisons it makes. For example, if the string we are looking for is “GAC” and the segment we are comparing it to is “TCG,” we know after the first comparison between the G and the T that this will not be a match. Therefore, we can move on to the next section of text and not waste time comparing the remaining two letters of the sequences since we know for certain they won’t match.
If we were to implement the optimization described above, what would be the best-case running time of the algorithm when checking for a word of length in a text of length if the algorithm finds that the word does not appear in the text?
First, let’s identify the best-case situation—the one with the fewest comparisons. We would make the fewest comparisons if the first letter of the sequence of text never matches with the first letter of the word. In this case, we would perform comparisons, so the best-case running time is .
The Rabin-Karp algorithm makes use of hash functions and the rolling hash technique. A hash function is essentially a function that maps one thing to a value. In particular, hashing can map data of arbitrary size to a value of fixed size.
Here is a crash course on hashing:
Hashing is a way to associate values using a hash function to map an input to an output. The purpose of a hash is to take a large piece of data and be able to be represented by a smaller form. Hashing is incredibly useful and but does have some downfalls, namely, collisions. The pigeonhole principle tells us that we can't put balls into buckets without having at least one bucket with two balls in it. With hashing, we can think of the inputs to a function as the balls and the buckets as the outputs of the function—some inputs must inevitably share an output value, and this is called a collision.
A rolling hash allows an algorithm to calculate a hash value without having to rehash the entire string. For example, when searching for a word in a text, as the algorithm shifts one letter to the right (as in the animation for brute force), instead of having to calculate the hash of the section of text[1:3] as it shifts from text[0:2], the algorithm can use a rolling hash to do an operation on the hash to get the new hash from the old hash.
Say you have a hash function that maps each letter in the alphabet to a unique prime number, . You are searching a text of length for a word of length . Let’s say that the text is the following string “abcdefghijklmnopqrstuvwxyz” and the word is “fgh”. How can we use a rolling hash to search for “fgh”?
At each step, we compare three letters of the text to the three letters of the word. At the first step, we can multiply to get the hash of the string “abc”. Similarly, the hash value of “fgh” is . Compare the hash value of “abc” with “fgh” and see that the numbers do not match.
To move onto the next iteration, we need to calculate the hash value of “bcd”. How can we do this? We could compute , but we would actually be repeating work we’ve already done!
We know and we know that . If we divide out the and multiply in the we can get the hash value of “bcd”. We compare this value with “fgh”, and so on.
Rabin-Karp uses only simple multiplications and additions in its rolling hash implementation.
All the operations are done modulo a prime number to avoid dealing with large numbers. For the sake of readability and simplicity, the modulo has been excluded, but the calculations still hold when modulo is present.
The Rabin-Karp Rolling Hash
is a constant, are the input characters, and is the number of characters there are in the string we are comparing (this is the length of the word).
Let’s use Rabin-Karp’s rolling hash to hash the alphabet. Here, will be , will be , and will represent the place in the alphabet where the character appears—so for “a” will be , and for “z” will be .
Let’s find the hash of “abc” and use that to find the hash of “bcd”:
To get the hash of “bcd”, we need to remove “a” and add “d”:
We will need to multiply by since we will be subtracting out the term that is currently associated with “a” and will need to now be associated with “b”. This will shift values to the left so that “d” will have the coefficient:
At each step, there are a constant number of operations (one subtraction, one multiplication, and one addition) and these are done in constant time, . When checking if a substring of the text is equal to the word, the algorithm just needs to see if the hash values are equal. This can also be done in constant time. Because the algorithm performs operations on each character of the text and there are characters in the text, this step takes time.
Here is one way to implement the Rabin-Karp algorithm in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
Assume the text is length and the length of the word is . The best- and average-case running time of Rabin-Karp is because the rolling hash step takes time and once the algorithm finds a potential match, it must verify each letter to make sure that the match is true and not a result of a hashing collision and therefore must check each of the letters in the word.
The worst-case running time of Rabin-Karp is . This would occur with an extremely awful hash function that resulted in a false positive at each step. Since whenever the algorithm thinks it found a match, it must verify each of the letters in the word, if there is a collision at each step, letters will be checked times resulting in a running time of . This can be avoided with a good choice of hash function.
When searching for a single pattern to match in a text, the Knuth–Morris–Pratt algorithm will be a faster choice. For matching multiple patterns, the Rabin-Karp algorithm paired with a Bloom filter can efficiently find multiple patterns in a text.
- , . Hash Function. Retrieved May 28, 2016, from https://en.wikipedia.org/wiki/Hash_function
- , . Rolling Hash. Retrieved May 28, 2016, from https://en.wikipedia.org/wiki/Rolling_hash
- , m. Rabin-Karp. Retrieved May 28, 2016, from https://github.com/mccricardo/Rabin-Karp/blob/master/rabin_karp.py
- , . Rabin–Karp algorithm. Retrieved May 29, 2016, from https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm