16. Rabin-Karp Algorithm Based on Hash
Description
The Rabin-Karp algorithm is an efficient substring search algorithm that uses hashing to quickly compare substrings with a given pattern. Its main idea is to compute hash values for substrings in the string and for the pattern, saving time on character-by-character comparisons when hash values do not match. If the hashes match, a direct character comparison is performed.
This algorithm is especially effective when finding all occurrences of a substring in a string or searching through large texts. It is also suitable for multiple searches with the same pattern, as the pattern hash can be precomputed.
How the Rabin-Karp Algorithm Works
- Preprocessing:
- Hash values are computed for the pattern and for all possible substrings of length equal to the pattern length in the main string.
- Polynomial hashing is typically used, where the hash of a string S of length m is calculated as:
hash(S) = (S[0] p^(m-1) + S[1] p^(m-2) + ... + S[m-1] * p^0) mod q where p is the hash base (usually a prime number) and q is a large prime number to reduce collision probability.
- Comparison:
- The hash of the pattern and the hash of each substring in the main string are computed.
- If the hashes match, a direct character-by-character check of the substring and pattern is performed. This is necessary because two different substrings can have the same hash value due to collisions.
- If the hashes do not match, the substring is automatically rejected.
- Sliding Window:
- The algorithm uses a "sliding window" technique to shift the substring along the string.
- With each shift, a new hash for the next substring is computed using the previous hash, which speeds up calculations.
Python Implementation
def rabin_karp_search(text, pattern):
n = len(text)
m = len(pattern)
p = 31
q = 10**9 + 7
pattern_hash = 0
for i in range(m):
pattern_hash = (pattern_hash * p + ord(pattern[i])) % q
text_hash = 0
for i in range(m):
text_hash = (text_hash * p + ord(text[i])) % q
matches = []
for i in range(n - m + 1):
if text_hash == pattern_hash:
if text[i:i + m] == pattern:
matches.append(i)
if i < n - m:
text_hash = (text_hash - ord(text[i]) * pow(p, m - 1, q)) % q
text_hash = (text_hash * p + ord(text[i + m])) % q
text_hash = (text_hash + q) % q
return matches
Rabin-Karp Algorithm in Practice
The Rabin-Karp algorithm runs in O(n ยท m) time in the worst case, where n is the length of the string and m is the length of the pattern. However, using a good hash function and minimizing collisions allows achieving an average running time of O(n + m), making it very efficient for many applications.
Code Explanation
- Initialization:
- We set the hash base
p = 31and the prime numberq = 10^9 + 7to minimize collision probability.
- Hash Computation:
- The hash for the pattern (
pattern_hash) is computed as the sum of character codes multiplied by powers of basep. - The hash for the first
mcharacters of the string is computed similarly.
- Search and Window Shift:
- The algorithm iterates through the string using a sliding window of length
m(the pattern length). - At each step, the old hash is updated considering the removal of the first character and addition of the next character.
- If the hashes match, we check whether the substring actually matches the pattern.
- Hash Correction:
- To update the hash when sliding the window, we remove the contribution of the outgoing character from the old hash and add the contribution of the incoming character, using modulo
qoperations to prevent overflow.
Advantages of Rabin-Karp Algorithm
- Speed for Multiple Searches:
- If the pattern remains constant and multiple searches are needed across different strings, Rabin-Karp is very efficient because the pattern hash is calculated once, and substring comparisons take O(1) time after each shift.
- Multi-Pattern Search:
- The algorithm can be adapted to search for multiple patterns simultaneously, which is useful for tasks like finding various patterns in a large body of text.
- Reduced Search Time:
- With a large number of matches or when working with big texts, the Rabin-Karp algorithm significantly speeds up search by eliminating unnecessary character comparisons.
Disadvantages
- Hash Collisions:
- The algorithm depends heavily on the quality of the hash function. Frequent collisions (different text fragments producing identical hashes) reduce efficiency due to required character checks.
- Implementation and Tuning:
- Good performance depends on choosing optimal hashing parameters (base
pand moduloq), which requires extra calculation and configuration.
Applications of Rabin-Karp Algorithm
- Text Search: Used for fast substring searching in text editors or large documents.
- Bioinformatics Pattern Matching: Useful for finding DNA or protein sequences in databases.
- Real-time Substring Search: In systems requiring continuous string updates and pattern searching over data streams.
Conclusion
The Rabin-Karp algorithm is a powerful substring search tool that speeds up searching via hashing. It is particularly valuable when processing large amounts of data or searching for multiple patterns.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me