The user wants a program that implements the Rabin-Karp rolling hash algorithm.
1. Understand the Core Algorithm:
Purpose: String matching (finding a pattern P inside a text T).
Mechanism: Hashing.
Calculate the hash of the pattern (hash_p).
Calculate the hash of the first m characters of the text (hash_t).
Slide a window of size m over the text.
Compare hash_p and hash_t.
If hashes match, compare the actual strings to avoid false positives (spurious hits).
Update hash_t for the next window using a "rolling" formula.
2. Key Formulas:
Base (d): The number of characters in the alphabet (e.g., 256 for ASCII).
PRIME (q): A prime number used for modulo arithmetic to keep hash values manageable and reduce collisions.
Initial Hash:hash=(d∗hash.
3. Language Selection:
Python is usually the most readable for explaining algorithms, but C++ or Java are often used for performance-critical contexts. I will provide the solution in Python for clarity, but maybe mention the logic applies generally. Let's stick to Python as the primary example.
4. Program Structure:
Input: Text string, Pattern string.
Preprocessing:
Get lengths (n,m).
Define constants (d=256,q=101 or larger).
Calculate h.
Initial Hashing:
Compute hash for pattern.
Compute hash for the first window of text.
Looping:
Iterate from 0 to .
5. Drafting the Code (Mental or Scratchpad):
python
def rabin_karp(text, pattern):
n = len(text)
m = len(pattern)
if m > n: return -1
# Constants
d = 256 # Alphabet size
q = 101 # Prime number
h = 1
for i in range(m - 1):
h = (h * d) % q
# Calc initial hashes
p_hash = 0
t_hash = 0
for i in range(m):
p_hash = (d * p_hash + ord(pattern[i])) % q
t_hash = (d * t_hash + ord(text[i])) % q
results = []
# Slide window
for i in range(n - m + 1):
if p_hash == t_hash:
# Check chars
if text[i:i+m] == pattern:
results.append(i)
# Rolling hash
if i < n - m:
t_hash = (d * (t_hash - ord(text[i]) * h) + ord(text[i + m])) % q
# Fix negative hash
if t_hash < 0:
t_hash += q
return results
6. Refining and Commenting:
The code looks solid. I need to explain the parameters (d, q) and the logic clearly.
q should be a reasonably large prime to avoid too many collisions, but 101 is standard for textbook examples. I'll stick with a generic prime or a larger one like 10 if I want to be fancy, but simple integers are easier to follow. Let's use for the example but mention that larger is better for production.
7. Final Output Generation:
Start with a brief explanation of the algorithm.
Provide the Python code.
Provide a usage example.
Explain the time complexity (O(m+n) average, O(mn) worst case).
Self-Correction during drafting:
Edge case: What if pattern length is 0? The loop range(m-1) works correctly for m=0 (empty range), but logically we should handle m=0 or just let Python handle it (usually searching for empty string returns everywhere). I'll keep it simple.
Edge case:n=0.
Negative hash issue: In Python, % handles negatives differently than C/Java. -5 % 10 is 5 in Python. In C, it might be -5. The code if t_hash < 0: t_hash += q is good practice regardless to make logic explicit, though technically redundant in Python if the modulo is calculated correctly. I will keep the check to make the algorithm portable in logic to C-style languages.
8. Structuring the Response:
Introduction: What is it?
Code: The implementation.
Explanation: Step-by-step breakdown of the code blocks.
Complexity: Big O notation.
Let's write the response.
Here is a complete implementation of the Rabin-Karp algorithm in Python.
The Algorithm Logic
Hashing: Instead of comparing the pattern against every substring character-by-character (which is slow), we calculate a numerical "hash" of the pattern.
Sliding Window: We calculate the hash of the first M characters in the text (where M is the length of the pattern).
Comparison: If the hash of the text window matches the hash of the pattern, we perform a character-by-character check to confirm (to protect against hash collisions).
Rolling: We slide the window one step to the right. Instead of recalculating the hash from scratch, we update the existing hash in O(1) time:
Subtract the contribution of the outgoing character.
Add the contribution of the incoming character.
Python Implementation
python
def rabin_karp(text, pattern, prime=101):
"""
Implements the Rabin-Karp algorithm to find occurrences of a pattern in a text.
Args:
text (str): The text to search within.
pattern (str): The pattern to search for.
prime (int): A prime number used for hash modulo calculation to avoid overflow.
Returns:
list: A list of starting indices where the pattern was found.
"""
n = len(text)
m = len(pattern)
indices = []
# Edge cases
if m == 0 or m > n:
return indices
# Constants
d = 256 # Number of characters in the input alphabet (ASCII)
# hash_p: Hash value for pattern
# hash_t: Hash value for current window of text
hash_p = 0
hash_t = 0
# h represents the value of the leading digit multiplier: d^(m-1) % prime
# This is needed to remove the leading character during the rolling step.
h = 1
# Calculate h = (d^(m-1)) % prime
for i in range(m - 1):
h = (h * d) % prime
# 1. Calculate the initial hash value for the pattern and the first window of text
for i in range(m):
hash_p = (d * hash_p + ord(pattern[i])) % prime
hash_t = (d * hash_t + ord(text[i])) % prime
# 2. Slide the pattern over text one by one
for i in range(n - m + 1):
# Check if hash values match
if hash_p == hash_t:
# 3. Confirm match character by character (collision check)
if text[i:i+m] == pattern:
indices.append(i)
# 4. Calculate hash for next window using the rolling technique
# Remove leading digit, add trailing digit
if i < n - m:
hash_t = (d * (hash_t - ord(text[i]) * h) + ord(text[i + m])) % prime
# We might get negative value of t, converting it to positive
if hash_t < 0:
hash_t = hash_t + prime
return indices
# --- Usage Example ---
if __name__ == "__main__":
T = "SOFTWARE ENGINEERING IS FUN"
P = "NEER"
result = rabin_karp(T, P)
if result:
print(f"Pattern found at index(es): {result}")
else:
print("Pattern not found.")
Key Implementation Details
The Modulo Operator (%):
We use a prime number to calculate the hash modulo. This keeps the hash values small (within integer limits) and reduces the likelihood of collisions. In the code, d represents the alphabet size (256 for extended ASCII).
The h Variable:
This represents the highest power of the base (dm−1) used in the polynomial hash. When we slide the window, we subtract the contribution of the character leaving the window. For example, if the window is "abc", 'a' contributed a⋅d2. To remove it, we subtract .
Complexity
Time Complexity: O(n+m) on average. In the worst case (where many spurious hits occur, e.g., searching "AAA" in "AAAAAAAA"), it becomes O(n×m).
Space Complexity: O(1) (excluding the storage for the result list).
+
char_val)%q
Highest Power of Base (h):h=d(m−1)%q. This is needed for removing the leading digit during the rolling step.
Rolling Hash Update:
Subtract the contribution of the outgoing character: (text[i]∗h)%q.
Add the contribution of the incoming character: text[i+m].
Handling Negative Modulo: Ensure the result is positive.
n−m
Check hash match.
If match, check character-by-character.
If not the last window, calculate rolling hash.
Output: Indices where matches occur.
9
+
7
101
Include ord() because Python strings are characters, not integers.
a⋅h
Negative Hash Correction:
In Python, the modulo operator behaves differently than in C or Java when dealing with negative numbers. However, mathematically, hash_t - ord(text[i]) * h can result in a negative number. We check for this and add the prime number back to wrap it around to the correct positive residue.