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.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Matches: 0 9 12
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Matches: 0 9 12
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Update a fixed-size window hash in constant time and verify only hash matches.
- 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.
