Skip to main content

Rabin Karp Algorithm

Definition​

The Rabin-Karp Algorithm is a string-searching algorithm that efficiently finds the occurrence of a pattern within a text. It's particularly useful when the pattern searching involves multiple occurrences in the text

Practice​

rabin_karp(text, pattern):
n = length(text)
m = length(pattern)
prime = a large prime number
base = a base value for the hash function

pattern_hash = hash(pattern) # Compute hash of the pattern
text_hash = hash(text[0:m]) # Compute hash of the initial substring of text

for i from 0 to n-m:
if pattern_hash == text_hash:
if pattern == text[i:i+m]:
print "Pattern found at index", i
if i < n-m:
text_hash = (text_hash - ord(text[i]) * base**m) * base + ord(text[i+m])

# Rolling hash function
hash(s):
hash_value = 0
for character in s:
hash_value = (hash_value * base + ord(character)) % prime
return hash_value