ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Search Text with the KMP Algorithm
Learn how to search text with the kmp algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Index = 10
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
const char text[] = "ABABDABACDABABCABAB", pattern[] = "ABABCABAB";
int n = (int) strlen(text), m = (int) strlen(pattern), prefix[20] = {0};
for (int i = 1, border = 0; i < m;) {
if (pattern[i] == pattern[border]) prefix[i++] = ++border;
else if (border) border = prefix[border - 1]; else prefix[i++] = 0;
}
int i = 0, j = 0;
while (i < n) {
if (text[i] == pattern[j]) { i++; j++; }
if (j == m) { printf("Index = %d\n", i - j); break; }
if (i < n && text[i] != pattern[j]) { if (j) j = prefix[j - 1]; else i++; }
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Index = 10
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use the prefix table to shift the pattern without rechecking confirmed characters.
- Display the computed result.
Use the prefix table to shift the pattern without rechecking confirmed characters.
EFFICIENCY
Time and space complexity
Time complexity
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.
