Write a program that implements the Rabin-Karp rolling hash algorithm.
- User
Write a program that implements the Rabin-Karp rolling hash algorithm.
Assistant
1. Understand the Goal: The user wants a program that implements the Rabin-Karp rolling hash algorithm. This usually means implementing the Rabin-Karp string search algorithm which utilizes the rolling hash to find a pattern within a text.
-
Identify the Core Components:
- Rolling Hash Function: This is the mathematical engine. It needs to compute the hash of the pattern and the hash of the first window of the text. Crucially, it needs to update the text hash in time when sliding the window.
- Modular Arithmetic: To prevent integer overflow, we use a large prime number as a modulus.
- Base: We need a base for the polynomial hash (often 256 for ASCII characters or a smaller prime like 101).
- Algorithm Logic:
- Precompute the highest power of the base used in the window (often denoted as or ).
- Calculate hash of the pattern () and the first window of text ().
- Slide the window:
- Compare and . If they match, compare actual strings (collision check).
- Update using the rolling formula: . Handle negative results.
- Repeat until the end of the text.
- Input/Output: A way to demonstrate the code works (e.g., a
mainfunction taking a text and a pattern).
-
Select a Language: Python is great for readability and high-level logic, but C++ or Java are often preferred for algorithms to show the low-level handling of modular arithmetic and overflow prevention. I will provide the solution in Python because it's the most accessible "pseudocode-like" executable language, but I'll ensure the implementation handles the modulus arithmetic correctly to reflect the true algorithm, rather than just slicing strings (which is ). I'll also provide a C++ version for robustness/performance demonstration, as that's often expected in competitive programming contexts. Let's stick to Python as the primary answer for clarity, maybe C++ as an alternative if requested, but usually, one good implementation is enough. I'll stick to Python but write it explicitly.
-
Drafting the Python Code:
- Parameters:
text,pattern,base(d),prime(q). - Edge case: Pattern longer than text.
- Variable initialization:
m: len(pattern)n: len(text)i,j: loop countersp: hash value for patternt: hash value for text windowh:
- Preprocessing:
- Calculate
h. - Calculate initial hash for pattern and text[0...m].
- Calculate
- Sliding Loop:
- If
p == t: Check char by char. - If match found: Print/Return index.
- Update hash for text window:
- Formula:
t = (d * (t - ord(text[i]) * h) + ord(text[i + m])) % q - Python's
%handles negatives differently than C++ (always non-negative result for positive modulus), so specific negative handling isn't strictly necessary in Python, but good to keep in mind.
- Formula:
- If
- Optimization: Since
ord()can be large, maybe just map 'a'-'z' to 0-25? No, general implementation handles ASCII usually. I'll useord().
- Parameters:
-
Refining the Explanation:
- Explain the math briefly (Horner's rule).
- Explain why the "rolling" part is .
- Explain the modulus.
- Explain the "Spurious Hit" (collision) check.
-
Writing the Code (Mental Check):
def rabin_karp(text, pattern, prime=101): d = 256 # base M = len(pattern) N = len(text) p = 0 # pattern hash t = 0 # text hash h = 1 # h = pow(d, M-1)%q for i in range(M-1): h = (h * d) % prime # Calc initial hashes for i in range(M): p = (d * p + ord(pattern[i])) % prime t = (d * t + ord(text[i])) % prime # Slide for i in range(N - M + 1): if p == t: # Check chars if text[i:i+M] == pattern: print("Found at", i) # Roll if i < N - M: t = (d * (t - ord(text[i]) * h) + ord(text[i + M])) % prime # Ensure positive if t < 0: t = t + prime-
Double Checking the Math:
- Formula for rolling: .
- In Python,
t - ord(text[i]) * hmight be negative. Python's modulo returns a non-negative result if the divisor is positive, sot = (negative_val) % primeworks correctly without manual adjustment. However, explicitly addingqif negative is a common habit from C/C++ that makes the logic clearer for beginners. I'll verify Python behavior.-5 % 3is1in Python. So explicit check isn't strictly needed, but I will add a comment about it or keep it minimal for Pythonic style.
-
Structuring the Output:
- Provide the Python code.
- Add comments explaining the steps.
- Provide a usage example.
- Briefly explain the Time Complexity ( average, worst).
-
Self-Correction during drafting:
- Issue: Should I handle the case where
textis shorter thanpattern? - Fix: Yes, add a guard clause at the start.
- Issue: What prime to use?
- Fix: 101 is the standard textbook example, but a large prime reduces collisions. I'll stick to a standard one or allow it as an argument.
- Issue: Should I handle the case where
-
Final Code Assembly: (Similar to the mental check above). I will also include the explanation of why the rolling hash works (subtract leading term, shift, add new term).
Let's verify the rolling hash update line again. Current window:
ABC. Next windowBCD. Hash(ABC) = . We want Hash(BCD) = . Step 1: Remove . Step 2: Multiply remainder by : . Step 3: Add . Correct. -
Final Polish: Ensure variable names are descriptive (
n,m,q,dare standard, buttext_len,pat_lenare clearer). I'll use standard textbook notations for brevity but explain them.(Self-Correction): The prompt asks for the "Rabin-Karp rolling hash algorithm". I should make sure to explicitly name the function
rabin_karp_search.Result generation... Here is a complete implementation of the Rabin-Karp algorithm in Python.
The Algorithm Logic
Rabin-Karp finds a pattern string inside a text string by converting the strings into integers (hashes).
- Hash the Pattern: Calculate the hash value of the search pattern.
- Rolling Hash: Calculate the hash of the first window in the text (same length as the pattern).
- Slide: Move the window across the text one character at a time. Instead of recalculating the hash from scratch, update the hash in time by subtracting the contribution of the outgoing character and adding the contribution of the incoming character.
- Check: If the text hash matches the pattern hash, perform a final string comparison to rule out false positives (collisions).
Python Implementation
def rabin_karp(text, pattern, prime=101, base=256): """ Implements the Rabin-Karp algorithm to find all occurrences of a pattern string within a text string. Args: text (str): The text to search within. pattern (str): The pattern to search for. prime (int): A prime number used for hashing (modulus). base (int): The number of characters in the input alphabet (256 for ASCII/extended ASCII). Returns: list: A list of starting indices where the pattern was found. """ n = len(text) m = len(pattern) indices = [] if m == 0 or m > n: return indices # Variables to store hash values hash_p = 0 # Hash value for pattern hash_t = 0 # Hash value for text window # h = (base^(m-1)) % prime # This is used to remove the leading digit when rolling the hash h = 1 for i in range(m - 1): h = (h * base) % prime # 1. Pre-processing: Calculate initial hash for pattern and first text window # The polynomial hash is: c0*b^(m-1) + c1*b^(m-2) ... + cm-1*b^0 for i in range(m): hash_p = (base * hash_p + ord(pattern[i])) % prime hash_t = (base * 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. Check for collisions (Spurious hits) # If hashes match, verify character by character if text[i:i + m] == pattern: indices.append(i) # 4. Calculate hash for next window (Rolling) # Remove leading digit, add trailing digit if i < n - m: hash_t = (base * (hash_t - ord(text[i]) * h) + ord(text[i + m])) % prime # We might get negative value of hash_t, converting it to positive if hash_t < 0: hash_t = hash_t + prime return indices # --- Usage Example --- if __name__ == "__main__": text_input = "ALGORITHM PROGRAMMING RABIN KARP ALGORITHM" pattern_input = "ALGORITHM" print(f"Text: {text_input}") print(f"Pattern: {pattern_input}") result = rabin_karp(text_input, pattern_input) if result: print(f"Pattern found at indices: {result}") else: print("Pattern not found.")Key Components Explained
base(d): Represents the alphabet size (256 covers standard ASCII). This determines the weight of the digits in our polynomial hash.prime(q): A prime number used as the modulus. This keeps the hash values manageable (preventing integer overflow in languages like C++ or Java) and reduces the likelihood of collisions.h: This pre-calculated value is . When we slide the window, the "oldest" character (the one leaving the window) was multiplied by this highest power. We subtractchar * hto effectively "shift" the remaining hash digits one place to the left.- Collision Check: Note the line
if text[i:i + m] == pattern. It is theoretically possible for two different strings to have the same hash value (a "spurious hit"). Therefore, Rabin-Karp requires a final full string comparison if the hashes match.
Complexity
- Time Complexity:
- Average/Best Case: , where is text length and is pattern length.
- Worst Case: (occurs if there are many hash collisions).
- Space Complexity: (ignoring the space needed to store the result indices).
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.