Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Write a program that implements the Rabin-Karp rolling hash algorithm.

  1. User

    Write a program that implements the Rabin-Karp rolling hash algorithm.

  2. GLM 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.

    1. 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 O(1)O(1) 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:
        1. Precompute the highest power of the base used in the window (often denoted as hh or powpow).
        2. Calculate hash of the pattern (pp) and the first window of text (tt).
        3. Slide the window:
          • Compare pp and tt. If they match, compare actual strings (collision check).
          • Update tt using the rolling formula: (d∗(t−oldchar∗h)+new_char)%q(d * (t - old_char * h) + new\_char) \% q. Handle negative results.
          • Repeat until the end of the text.
      • Input/Output: A way to demonstrate the code works (e.g., a main function taking a text and a pattern).
    2. 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 O(k)O(k)). 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.

    3. 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 counters
        • p: hash value for pattern
        • t: hash value for text window
        • h: dm−1mod  qd^{m-1} \mod q
      • Preprocessing:
        • Calculate h.
        • Calculate initial hash for pattern and text[0...m].
      • 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.
      • Optimization: Since ord() can be large, maybe just map 'a'-'z' to 0-25? No, general implementation handles ASCII usually. I'll use ord().
    4. Refining the Explanation:

      • Explain the math briefly (Horner's rule).
      • Explain why the "rolling" part is O(1)O(1).
      • Explain the modulus.
      • Explain the "Spurious Hit" (collision) check.
    5. 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
    
    1. Double Checking the Math:

      • Formula for rolling: Ti+1=(d(Ti−Ti_start⋅h)+Ti_end)mod  qT_{i+1} = (d(T_i - T_{i\_start} \cdot h) + T_{i\_end}) \mod q.
      • In Python, t - ord(text[i]) * h might be negative. Python's modulo returns a non-negative result if the divisor is positive, so t = (negative_val) % prime works correctly without manual adjustment. However, explicitly adding q if negative is a common habit from C/C++ that makes the logic clearer for beginners. I'll verify Python behavior. -5 % 3 is 1 in Python. So explicit check isn't strictly needed, but I will add a comment about it or keep it minimal for Pythonic style.
    2. Structuring the Output:

      • Provide the Python code.
      • Add comments explaining the steps.
      • Provide a usage example.
      • Briefly explain the Time Complexity (O(n+m)O(n+m) average, O(nm)O(nm) worst).
    3. Self-Correction during drafting:

      • Issue: Should I handle the case where text is shorter than pattern?
      • 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.
    4. 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 window BCD. Hash(ABC) = A⋅d2+B⋅d+CA \cdot d^2 + B \cdot d + C. We want Hash(BCD) = B⋅d2+C⋅d+DB \cdot d^2 + C \cdot d + D. Step 1: Remove A⋅d2A \cdot d^2. Step 2: Multiply remainder by dd: (B⋅d+C)⋅d=B⋅d2+C⋅d(B \cdot d + C) \cdot d = B \cdot d^2 + C \cdot d. Step 3: Add DD. Correct.

    5. Final Polish: Ensure variable names are descriptive (n, m, q, d are standard, but text_len, pat_len are 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 PP inside a text string TT by converting the strings into integers (hashes).

    1. Hash the Pattern: Calculate the hash value of the search pattern.
    2. Rolling Hash: Calculate the hash of the first window in the text (same length as the pattern).
    3. Slide: Move the window across the text one character at a time. Instead of recalculating the hash from scratch, update the hash in O(1)O(1) time by subtracting the contribution of the outgoing character and adding the contribution of the incoming character.
    4. 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

    1. base (d): Represents the alphabet size (256 covers standard ASCII). This determines the weight of the digits in our polynomial hash.
    2. 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.
    3. h: This pre-calculated value is basem−1mod  primebase^{m-1} \mod prime. When we slide the window, the "oldest" character (the one leaving the window) was multiplied by this highest power. We subtract char * h to effectively "shift" the remaining hash digits one place to the left.
    4. 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: O(n+m)O(n + m), where nn is text length and mm is pattern length.
      • Worst Case: O(nm)O(nm) (occurs if there are many hash collisions).
    • Space Complexity: O(1)O(1) (ignoring the space needed to store the result indices).

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.