Program for Rabin-Karp Algorithm for Pattern Searching in C

In this problem, we are given two strings − a text and a pattern. Our task is to create a program for Rabin-Karp algorithm for pattern search, which will find all the occurrences of the pattern in the text string.

The Rabin-Karp algorithm is an efficient string matching algorithm that uses hashing to find patterns. It works by computing hash values for the pattern and text windows, comparing them first before doing character-by-character matching.

Syntax

void rabinKarpSearch(char pattern[], char text[]);
// Where pattern is the string to search for
// And text is the string to search in

How It Works

The algorithm follows these steps −

  • Hash Calculation: Compute hash values for the pattern and the first window of text
  • Rolling Hash: Slide the window and update hash efficiently using rolling hash technique
  • Hash Comparison: If hash values match, verify by comparing individual characters
  • Report Match: If characters also match, report the position
Text: "xyztrwqxyzfg" Pattern: "xyz" xyz Match 1: at index 0 xyz Match 2: at index 7 0 1 2 3 4 5 6 7 8 9 10 11

Example

This example demonstrates the Rabin-Karp algorithm to find all occurrences of a pattern in the given text −

#include <stdio.h>
#include <string.h>

#define BASE 256
#define PRIME 103

void rabinKarpSearch(char pattern[], char text[]) {
    int patternLen = strlen(pattern);
    int textLen = strlen(text);
    int patternHash = 0;
    int textHash = 0;
    int h = 1;
    int i, j;
    
    /* Calculate h = pow(BASE, patternLen-1) % PRIME */
    for (i = 0; i < patternLen - 1; i++)
        h = (h * BASE) % PRIME;
    
    /* Calculate hash value for pattern and first window of text */
    for (i = 0; i < patternLen; i++) {
        patternHash = (BASE * patternHash + pattern[i]) % PRIME;
        textHash = (BASE * textHash + text[i]) % PRIME;
    }
    
    /* Slide the pattern over text one by one */
    for (i = 0; i <= textLen - patternLen; i++) {
        /* Check if hash values match */
        if (patternHash == textHash) {
            /* Check for characters one by one */
            for (j = 0; j < patternLen; j++) {
                if (text[i + j] != pattern[j])
                    break;
            }
            
            /* If all characters matched */
            if (j == patternLen)
                printf("Pattern found at index %d<br>", i);
        }
        
        /* Calculate hash value for next window */
        if (i < textLen - patternLen) {
            textHash = (BASE * (textHash - text[i] * h) + text[i + patternLen]) % PRIME;
            
            /* Handle negative hash values */
            if (textHash < 0)
                textHash = textHash + PRIME;
        }
    }
}

int main() {
    char text[] = "xyztrwqxyzfg";
    char pattern[] = "xyz";
    
    printf("Text: %s<br>", text);
    printf("Pattern: %s<br>", pattern);
    printf("Search Results:<br>");
    
    rabinKarpSearch(pattern, text);
    
    return 0;
}
Text: xyztrwqxyzfg
Pattern: xyz
Search Results:
Pattern found at index 0
Pattern found at index 7

Key Points

  • Time Complexity: Average case O(n + m), worst case O(n*m) where n is text length and m is pattern length
  • Space Complexity: O(1) as it uses constant extra space
  • Rolling Hash: Efficiently computes hash for next window in O(1) time
  • Prime Modulus: Using a prime number (103) reduces hash collisions

Conclusion

The Rabin-Karp algorithm is efficient for pattern searching, especially when searching for multiple patterns. It uses rolling hash technique to achieve good average-case performance and is particularly useful in applications like plagiarism detection.

Updated on: 2026-03-15T12:50:39+05:30

643 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements