Content deleted Content added
Cognoscent (talk | contribs) |
m →Hash function used: {{pre}} |
||
(17 intermediate revisions by 12 users not shown) | |||
Line 1:
{{Short description|String searching algorithm}}
{{no footnotes|date=September 2018}}
{{Infobox algorithm
|name = Rabin-Karp algorithm
|class = [[string-searching algorithm|String searching]]
|image = <!-- filename only, no "File:" or "Image:" prefix, and no enclosing [[brackets]] -->
|caption =
|data =
|time = <math>O(mn)</math> plus <math>O(m)</math> preprocessing time
|best-time =
|average-time = <math>O(n)</math>
|space = <math>O(1)</math>
}}
In [[computer science]], the '''Rabin–Karp algorithm''' or '''Karp–Rabin algorithm''' is a [[string-searching algorithm]] created by {{harvs|first1=Richard M.|last1=Karp|author1-link=Richard M. Karp|first2=Michael O.|last2=Rabin|author2-link=Michael O. Rabin|year=1987|txt}} that uses [[Hash function|hashing]] to find an exact match of a pattern string in a text. It uses a [[rolling hash]] to quickly filter out positions of the text that cannot match the pattern, and then checks for a match at the remaining positions. Generalizations of the same idea can be used to find more than one match of a single pattern, or to find matches for more than one pattern.
Line 16 ⟶ 28:
A hash function is a function which converts every string into a numeric value, called its ''hash value''; for example, we might have <code>hash("hello")=5</code>. If two strings are equal, their hash values are also equal. For a well-designed hash function, the inverse is true, in an approximate sense: strings that are unequal are very unlikely to have equal hash values. The Rabin–Karp algorithm proceeds by computing, at each position of the text, the hash value of a string starting at that position with the same length as the pattern. If this hash value equals the hash value of the pattern, it performs a full comparison at that position.
In order for this to work well, the hash function should be selected randomly from a family of hash functions that are unlikely to produce many [[false positive]]s, that is, positions of the text which have the same hash value as the pattern but do not actually match the pattern. These positions contribute to the running time of the algorithm unnecessarily, without producing a match. Additionally, the hash function used should be a [[rolling hash]], a hash function whose value can be quickly updated from each position of the text to the next. Recomputing the hash function from scratch at each position would be too slow.
==The algorithm==
Line 35 ⟶ 47:
Lines 2, 4, and 6 each require [[Big-O notation|O]](''m'') time. However, line 2 is only executed once, and line 6 is only executed if the hash values match, which is unlikely to happen more than a few times. Line 5 is executed O(''n'') times, but each comparison only requires constant time, so its impact is O(''n''). The issue is line 4.
Naively computing the hash value for the substring <code>s[i+1..i+m]</code> requires
The trick can be exploited using a [[rolling hash]]. A rolling hash is a hash function specially designed to enable this operation. A trivial (but not very good) rolling hash function just adds the values of each character in the substring. This rolling hash formula can compute the next hash value from the previous value in constant time:
Line 43 ⟶ 55:
This simple function works, but will result in statement 5 being executed more often than other more sophisticated rolling hash functions such as those discussed in the next section.
Good performance requires a good hashing function for the encountered data. If the hashing is poor (such as producing the same hash value for every input), then line 6 would be executed
== Hash function used ==
{{main | Rabin fingerprint}}
The key to the Rabin–Karp algorithm's performance is the efficient computation of [[hash value]]s of the successive substrings of the text. The [[Rabin fingerprint]] is a popular and effective rolling hash function. The hash function described here is not a Rabin fingerprint, but it works equally well. It treats every substring as a number in some base, the base being usually the size of the character set.
For example, if the substring is "hi", the base is 256, and prime modulus is 101, then the hash value would be
[(104 × 256 ) %{{efn|name=mod}} 101 + 105] % 101 = 65
([[ASCII]] of 'h' is 104 and of 'i' is 105)
<sub> '%' is 'mod' or modulo, or remainder after integer division, operator </sub>▼
Technically, this algorithm is only similar to the true number in a non-decimal system representation, since for example we could have the "base" less than one of the "digits". See [[hash function]] for a much more detailed discussion. The essential benefit achieved by using a [[rolling hash]] such as the Rabin fingerprint is that it is possible to compute the hash value of the next substring from the previous one by doing only a constant number of operations, independent of the substrings' lengths.
Line 61 ⟶ 71:
hash("abr") = [ ( [ ( [ (97 × 256) % 101 + 98 ] % 101 ) × 256 ] % 101 ) + 114 ] % 101 = 4
We can then compute the hash of the next substring, "bra", from the hash of "abr" by subtracting the number added for the first 'a' of "abr", i.e. 97 × 256<sup>2</sup>, multiplying by the base and adding for the last a of "bra", i.e. 97 × 256<sup>0</sup>. Like so:
{{pre|style=font-size:95%|1=
}}
<sub> * (-ve avoider) = "underflow avoider". Necessary if using unsigned integers for calculations. Because we know all hashes <math>h \leq p</math> for prime modulus $p$, we can ensure no underflow by adding p to the old hash before subtracting the value corresponding to the old 'a' (mod p).</sub>▼
<sub> the last '* 256' is the shift of the subtracted hash to the left </sub>▼
<sub> although ((256%101)*256)%101 is the same as 256<sup>2</sup> % 101, to avoid overflowing integer maximums when the pattern string is longer (e.g. 'Rabin-Karp' is 10 characters, 256<sup>9</sup> is the offset without modulation ), the pattern length base offset is pre-calculated in a loop, modulating the result each iteration </sub> ▼
If we are matching the search string "bra", using similar calculation of hash("abr"),
Line 81 ⟶ 82:
If the substrings in question are long, this algorithm achieves great savings compared with many other hashing schemes.
Theoretically, there exist other algorithms that could provide convenient recomputation, e.g. multiplying together ASCII values of all characters so that shifting substring would only entail dividing the previous hash by the first character value, then multiplying by the new last character's value. The limitation, however, is the limited size of the integer [[data type]] and the necessity of using [[modular arithmetic]] to scale down the hash results
== Multiple pattern search ==
The Rabin–Karp algorithm is inferior for single pattern searching to [[Knuth–Morris–Pratt algorithm]], [[Boyer–Moore string
To find any of a large number, say ''k'', fixed length patterns in a text, a simple variant of the Rabin–Karp algorithm uses a [[Bloom filter]] or a [[set data structure]] to check whether the hash of a given string belongs to a set of hash values of patterns we are looking for:
Line 103 ⟶ 104:
We assume all the substrings have a fixed length ''m''.
A naïve way to search for ''k'' patterns is to repeat a single-pattern search taking
==Notes==
{{notelist|refs=
▲
▲
▲
▲
}}
==References==
{{Reflist}}
* {{Cite journal |last1=Karp|first1= Richard M. | author-link=Richard Karp | last2=Rabin|first2=Michael O.|author2-link=Michael O. Rabin | title=Efficient randomized pattern-matching algorithms |date=March 1987 |journal=IBM Journal of Research and Development |volume=31 |issue=2|pages=249–260|doi=10.1147/rd.312.0249 |citeseerx = 10.1.1.86.9502}}▼
===Sources===
* {{Cite book | last1 = Cormen | first1 = Thomas H. | author-link1 = Thomas H. Cormen | author-link2 = Charles E. Leiserson | last2 = Leiserson | first2 = Charles E. | author-link3 = Ronald L. Rivest | last3 = Rivest | first3 = Ronald L. | author-link4 = Clifford Stein | last4 = Stein | first4 = Clifford |title=[[Introduction to Algorithms]] |orig-year=1990 |edition=2nd |date=2001-09-01 |publisher=MIT Press |___location=[[Cambridge, Massachusetts]] |isbn=978-0-262-03293-3 |pages=911–916 |chapter=The Rabin–Karp algorithm}}▼
* {{cite book| first1 = K. Selçuk | last1 = Candan | first2 = Maria Luisa | last2 = Sapino|title=Data Management for Multimedia Retrieval|url=https://books.google.com/books?id=Uk9tyXgQME8C&pg=PA205| date = 2010|publisher=Cambridge University Press|isbn=978-0-521-88739-7|pages=205–206}} (for the Bloom filter extension)
▲* {{Cite book | last1 = Cormen | first1 = Thomas H. | author-link1 = Thomas H. Cormen | author-link2 = Charles E. Leiserson | last2 = Leiserson | first2 = Charles E. | author-link3 = Ronald L. Rivest | last3 = Rivest | first3 = Ronald L. | author-link4 = Clifford Stein | last4 = Stein | first4 = Clifford |title=[[Introduction to Algorithms]] |orig-year=1990 |edition=2nd |date=2001-09-01 |publisher=MIT Press |___location=[[Cambridge, Massachusetts]] |isbn=978-0-262-03293-3 |pages=911–916 |chapter=The Rabin–Karp algorithm}}
▲* {{Cite journal |last1=Karp|first1= Richard M. | author-link=Richard Karp | last2=Rabin|first2=Michael O.|author2-link=Michael O. Rabin | title=Efficient randomized pattern-matching algorithms |date=March 1987 |journal=IBM Journal of Research and Development |volume=31 |issue=2|pages=249–260|doi=10.1147/rd.312.0249 |citeseerx = 10.1.1.86.9502}}
==External links==
|