ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING

Search with Rabin–Karp Rolling Hash

Learn how to search with rabin–karp rolling hash using a clear C program.

AdvancedPattern matchingString preprocessing

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Matches: 0 9 12

COMPLETE C PROGRAM

Complete C implementation

ads-rabin-karp-search.c
Open in compiler
#include <stdio.h>
#include <string.h>

int main(void)
{
    const char text[] = "AABAACAADAABAABA", pattern[] = "AABA";
    int n = (int) strlen(text), m = (int) strlen(pattern), base = 256, prime = 101;
    int high = 1, pattern_hash = 0, window_hash = 0;
    for (int i = 0; i < m - 1; i++) high = (high * base) % prime;
    for (int i = 0; i < m; i++) { pattern_hash = (base * pattern_hash + pattern[i]) % prime; window_hash = (base * window_hash + text[i]) % prime; }
    printf("Matches:");
    for (int start = 0; start <= n - m; start++) {
        if (pattern_hash == window_hash && strncmp(text + start, pattern, (size_t) m) == 0) printf(" %d", start);
        if (start < n - m) { window_hash = (base * (window_hash - text[start] * high) + text[start + m]) % prime; if (window_hash < 0) window_hash += prime; }
    }
    putchar('\n'); return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Matches: 0 9 12
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Update a fixed-size window hash in constant time and verify only hash matches.
  3. Display the computed result.

Update a fixed-size window hash in constant time and verify only hash matches.

EFFICIENCY

Time and space complexity

Time complexity

Average O(n + m)

Auxiliary space

O(pattern length)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.