ADVANCED DATA STRUCTURES PROGRAM • LEVEL 11 — STRING PATTERN MATCHING
Build the KMP Prefix Table
Learn how to build the kmp prefix table using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 0 1 2 0 1 2 3 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <string.h>
int main(void)
{
const char pattern[] = "ABABCABAB";
int length = (int) strlen(pattern), prefix[20] = {0};
for (int index = 1, border = 0; index < length;) {
if (pattern[index] == pattern[border]) prefix[index++] = ++border;
else if (border) border = prefix[border - 1];
else prefix[index++] = 0;
}
for (int index = 0; index < length; index++) printf("%d%c", prefix[index], index == length - 1 ? '\n' : ' ');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 0 1 2 0 1 2 3 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Reuse the longest proper prefix that is also a suffix after each mismatch.
- Display the computed result.
Reuse the longest proper prefix that is also a suffix after each mismatch.
EFFICIENCY
Time and space complexity
Time complexity
O(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.
