DS Lab · Experiment 19
Knuth-Morris-Pratt (KMP) pattern matching
CPattern matchingJNTUH R22 · CS306PC
Aim
To write a C program that finds every occurrence of a pattern in a text using the Knuth-Morris-Pratt algorithm, printing the prefix (failure) table of the pattern and all positions where the pattern is found.
Algorithm
- Read the text (length n) and the pattern (length m).
- Build the prefix table
lps:lps[i]is the length of the longest proper prefix ofpattern[0..i]that is also a suffix of it. Setlps[0] = 0andlen = 0. - For i from 1 to m − 1: if
pattern[i] == pattern[len], increase len and setlps[i] = len. Otherwise, if len > 0, setlen = lps[len - 1]and compare again without moving i; if len is 0, setlps[i] = 0and move on. - Search: keep i on the text and j on the pattern, both starting at 0.
- If
text[i] == pattern[j], move both forward. If j reaches m, report a match at index i − m and setj = lps[m - 1]to look for the next (possibly overlapping) match. - On a mismatch, if j > 0 set
j = lps[j - 1](i stays where it is); if j is 0, move i forward. - Print the number of matches.
Program
#include <stdio.h>
#include <string.h>
#define MAX_TEXT 200
#define MAX_PATTERN 50
int read_line(const char *prompt, char *buf, int size) {
printf("%s", prompt);
if (fgets(buf, size, stdin) == NULL) {
return 0;
}
buf[strcspn(buf, "\n")] = '\0';
return 1;
}
/* lps[i] = length of the longest proper prefix of pat[0..i]
that is also a suffix of pat[0..i] */
void compute_lps(const char *pat, int m, int lps[]) {
int len = 0;
int i = 1;
lps[0] = 0;
while (i < m) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
} else if (len > 0) {
len = lps[len - 1]; /* try a shorter prefix; i does not move */
} else {
lps[i] = 0;
i++;
}
}
}
int kmp_search(const char *text, int n, const char *pat, int m, const int lps[]) {
int i = 0, j = 0, matches = 0;
while (i < n) {
if (text[i] == pat[j]) {
i++;
j++;
if (j == m) {
printf("Pattern found at index %d\n", i - m);
matches++;
j = lps[m - 1]; /* continue, allowing overlapping matches */
}
} else if (j > 0) {
j = lps[j - 1]; /* text pointer i never moves back */
} else {
i++;
}
}
return matches;
}
int main(void) {
char text[MAX_TEXT], pat[MAX_PATTERN];
int lps[MAX_PATTERN];
if (!read_line("Enter the text: ", text, MAX_TEXT) ||
!read_line("Enter the pattern: ", pat, MAX_PATTERN)) {
printf("Invalid input\n");
return 1;
}
int n = (int)strlen(text);
int m = (int)strlen(pat);
if (m == 0 || m > n) {
printf("The pattern must be non-empty and not longer than the text\n");
return 1;
}
compute_lps(pat, m, lps);
printf("\nPrefix (LPS) table:\n");
printf("Index : ");
for (int i = 0; i < m; i++) {
printf("%2d ", i);
}
printf("\nChar : ");
for (int i = 0; i < m; i++) {
printf("%2c ", pat[i]);
}
printf("\nLPS : ");
for (int i = 0; i < m; i++) {
printf("%2d ", lps[i]);
}
printf("\n\n");
int matches = kmp_search(text, n, pat, m, lps);
if (matches == 0) {
printf("Pattern not found\n");
} else {
printf("Total matches: %d\n", matches);
}
return 0;
}Output
Overlapping matches
Enter the text: ABABABCABAB
Enter the pattern: ABAB
Prefix (LPS) table:
Index : 0 1 2 3
Char : A B A B
LPS : 0 0 1 2
Pattern found at index 0
Pattern found at index 2
Pattern found at index 7
Total matches: 3One match after partial matches
Enter the text: ABCABCABCABCD
Enter the pattern: ABCABCD
Prefix (LPS) table:
Index : 0 1 2 3 4 5 6
Char : A B C A B C D
LPS : 0 0 0 1 2 3 0
Pattern found at index 6
Total matches: 1Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
Index positions start at 0. In the first run "ABAB" is found at 0, 2 and 7; the match at 2 overlaps the one at 0, and KMP finds it because after a match it keeps the last two matched characters (j = lps[3] = 2) instead of starting over.
Checking the second table by hand: for "ABCABCD", the prefix "ABC" reappears at index 3, so lps[3..5] is 1, 2, 3; "D" breaks it, so lps[6] is 0. In the second run the pattern matches six characters at index 0 and fails at "D". Instead of starting again at index 1, KMP uses lps[5] = 3 and continues as if "ABC" were already matched, so the text pointer never goes back.
Common mistakes
Setting
lps[i] = 0as soon as a mismatch happens while building the table. Iflen > 0, first fall back tolen = lps[len - 1]and compare again.Moving the text index
ibackwards after a mismatch. In KMP only the pattern indexjfalls back; that is why it is O(n + m).Setting
j = 0after a full match. That misses overlapping matches; usej = lps[m - 1].Counting the whole string as its own prefix. LPS uses proper prefixes, which are shorter than the string, so
lps[0]is always 0.
Viva questions
Try to answer each one aloud before you open it.
What does the LPS (prefix or failure) table store?
For each position i in the pattern, the length of the longest proper prefix of
pattern[0..i]that is also a suffix of it. It tells KMP how much of the pattern is still matched after a mismatch.What is the time complexity of KMP?
O(m) to build the table and O(n) to search, so O(n + m) in total, even in the worst case.
Why is KMP better than the naive (brute-force) method?
The naive method moves the pattern one place and compares again from the start, which can take O(nm) time. KMP never moves back in the text, because the LPS table tells it where to continue in the pattern.
What is the LPS table of "AABAAA"?
0 1 0 1 2 2.
How does KMP compare with Boyer-Moore?
KMP scans the text left to right and guarantees O(n + m). Boyer-Moore compares right to left and can skip large parts of the text, so it is often faster on ordinary text with a large alphabet, though its simple versions have a worse worst case.