Knuth-Morris-Pratt (KMP) Algorithm in C++
The Knuth-Morris-Pratt (KMP) Algorithm is an efficient pattern matching algorithm used to search for a pattern inside a larger text. It improves upon Naive Pattern Matching by avoiding unnecessary comparisons. KMP uses information about the pattern itself through an array called LPS (Longest Proper Prefix which is also a Suffix). Its time complexity is O(n + m), where n is the length of the text and m is the length of the pattern.
1. What Is the KMP Algorithm?
KMP is a string searching algorithm that finds all occurrences of a pattern in a text without repeatedly comparing characters that are already known to match.
In the Naive algorithm, when a mismatch occurs, the pattern is shifted by one position. This may cause previously matched characters to be compared again.
KMP solves this problem by using the structure of the pattern to decide how far the pattern can be shifted. It does not move the text pointer backward.
Example
Text:
ABABDABACDABABCABAB
Pattern:
ABABCABAB
KMP searches for the pattern and identifies its starting index as 10.
Pattern found at index 10
2. Why Do We Need KMP?
Consider a text and pattern with several repeated characters. The Naive algorithm may compare the same characters multiple times after a mismatch.
Text:
AAAAABAAAAA
Pattern:
AAAAB
The Naive algorithm may repeatedly compare the initial A characters while shifting the pattern one position at a time.
KMP remembers how much of the pattern has already matched. It uses this information to skip comparisons that are guaranteed to be unnecessary.
3. What Is LPS Array?
LPS stands for Longest Proper Prefix which is also a Suffix.
For every position in the pattern, the LPS array stores the length of the longest proper prefix of the substring ending at that position that is also a suffix of that substring.
Understanding Prefix and Suffix
- Prefix: A sequence of characters that starts from the beginning of a string.
- Suffix: A sequence of characters that ends at the last position of a string.
- Proper Prefix: A prefix that is not equal to the complete string.
Example: String ABAB
Prefixes:
A
AB
ABA
Suffixes:
B
AB
BAB
The common proper prefix and suffix is AB. Its length is 2.
Therefore, LPS value = 2.
4. How to Build the LPS Array
The LPS array is calculated before searching the pattern in the text.
We use two variables:
- len: Length of the current longest prefix that is also a suffix.
- i: Current position in the pattern.
Rules for Building LPS
- The first LPS value is always 0.
- If the current characters match, increase len and store it in LPS[i].
- If they do not match and len is greater than 0, update len to LPS[len - 1].
- If they do not match and len is 0, store 0 and move to the next position.
Example
Pattern:
ABABCABAB
The LPS array is:
| Index | Character | Substring | LPS Value |
|---|---|---|---|
| 0 | A | A | 0 |
| 1 | B | AB | 0 |
| 2 | A | ABA | 1 |
| 3 | B | ABAB | 2 |
| 4 | C | ABABC | 0 |
| 5 | A | ABABCA | 1 |
| 6 | B | ABABCAB | 2 |
| 7 | A | ABABCABA | 3 |
| 8 | B | ABABCABAB | 4 |
Final LPS array:
0 0 1 2 0 1 2 3 4
5. C++ Program to Build the LPS Array
The following function calculates the LPS array for a given pattern.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void buildLPS(string pattern, vector<int>& lps) {
int m = pattern.length();
lps[0] = 0;
int len = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
int main() {
string pattern = "ABABCABAB";
vector<int> lps(pattern.length(), 0);
buildLPS(pattern, lps);
cout << "LPS Array: ";
for (int value : lps) {
cout << value << " ";
}
return 0;
}
Output
LPS Array: 0 0 1 2 0 1 2 3 4
6. How KMP Pattern Searching Works
After building the LPS array, KMP searches for the pattern inside the text using two indexes:
- i: Current index in the text.
- j: Current index in the pattern.
Searching Rules
- If text[i] equals pattern[j], increase both i and j.
- If j reaches the pattern length, a complete match is found.
- After a match, update j to lps[j - 1] to continue searching for overlapping matches.
- If a mismatch occurs and j is greater than 0, update j to lps[j - 1].
- If a mismatch occurs and j is 0, move i forward.
7. Complete KMP Algorithm in C++
This complete program builds the LPS array and searches for every occurrence of the pattern in the text.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void buildLPS(const string& pattern,
vector<int>& lps) {
int m = pattern.length();
int len = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(const string& text,
const string& pattern) {
int n = text.length();
int m = pattern.length();
if (m == 0) {
cout << "Empty pattern";
return;
}
if (m > n) {
cout << "Pattern not found";
return;
}
vector<int> lps(m, 0);
buildLPS(pattern, lps);
int i = 0;
int j = 0;
bool found = false;
while (i < n) {
if (text[i] == pattern[j]) {
i++;
j++;
}
if (j == m) {
cout << "Pattern found at index "
<< i - j << endl;
found = true;
j = lps[j - 1];
}
else if (i < n &&
text[i] != pattern[j]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (!found) {
cout << "Pattern not found";
}
}
int main() {
string text = "ABABDABACDABABCABAB";
string pattern = "ABABCABAB";
KMPSearch(text, pattern);
return 0;
}
Output
Pattern found at index 10
8. Dry Run of KMP Algorithm
Consider the following input:
Text = ABABDABACDABABCABAB
Pattern = ABABCABAB
The LPS array for the pattern is:
0 0 1 2 0 1 2 3 4
Initially, both pointers start at index 0. Whenever characters match, both pointers move forward. When a mismatch occurs, the LPS array determines the next pattern position.
| Step | Text Character | Pattern Character | Action |
|---|---|---|---|
| 1 | A | A | Match, move both pointers |
| 2 | B | B | Match, move both pointers |
| 3 | A | A | Match, move both pointers |
| 4 | B | B | Match, move both pointers |
| 5 | D | C | Mismatch, use LPS |
| 6 | D | A | Mismatch, move text pointer |
| 7 | A | A | Match, continue |
| 8 | B | B | Match, continue |
| 9 | A | A | Match, continue |
| 10 | C | B | Mismatch, use LPS |
| 11 | C | A | Mismatch, move text pointer |
| 12 | D | A | Mismatch, move text pointer |
| 13 onward | Remaining characters | Remaining pattern | Complete match at index 10 |
After the required comparisons, the complete pattern is found starting at index 10.
Pattern found at index 10
9. Handling Multiple and Overlapping Matches
KMP can find multiple occurrences of a pattern, including overlapping occurrences.
Example
Text:
AAAAA
Pattern:
AAA
LPS Array:
0 1 2
Matching positions:
0, 1, 2
After finding a complete match, KMP sets j to lps[j - 1]. This allows the algorithm to continue searching without missing overlapping occurrences.
10. Time and Space Complexity
Let n be the length of the text and m be the length of the pattern.
| Operation | Time Complexity |
|---|---|
| Building LPS Array | O(m) |
| Searching Pattern | O(n) |
| Total Time | O(n + m) |
Auxiliary Space: O(m) for storing the LPS array.
The algorithm also uses a constant number of additional variables.
11. KMP vs Naive Pattern Matching
| Feature | Naive Algorithm | KMP Algorithm |
|---|---|---|
| Approach | Checks every possible alignment | Uses LPS information |
| Preprocessing | Not required | Builds an LPS array |
| Worst-Case Time | O(n × m) | O(n + m) |
| Auxiliary Space | O(1) | O(m) |
| Repeated Comparisons | May occur frequently | Avoided using LPS |
| Implementation | Simple | More complex |
12. Common Mistakes in KMP
- Incorrect LPS calculation: Every LPS value must represent the longest proper prefix that is also a suffix.
- Moving the text pointer backward: KMP never moves the text pointer backward during searching.
- Incorrect mismatch handling: When j is greater than zero, update j using lps[j - 1].
- Incorrect match handling: After finding a match, update j to lps[j - 1] to continue searching.
- Accessing an invalid index: Check that j is less than the pattern length before comparing pattern[j].
- Ignoring empty patterns: Handle an empty pattern before accessing lps[0] or pattern[0].
13. Applications of KMP Algorithm
- Searching for words in large text documents.
- Text editors and search utilities.
- DNA sequence matching.
- Searching repeated character patterns.
- Plagiarism detection systems as one component of text analysis.
- Information retrieval systems.
- Efficient string matching in programming problems.
14. Practice Questions
- Implement the LPS array construction algorithm.
- Implement KMP to find the first occurrence of a pattern.
- Find all occurrences of a pattern using KMP.
- Modify KMP to count the number of matches.
- Use KMP to find overlapping pattern occurrences.
- Calculate the LPS array for the pattern ABABAC.
- Calculate the LPS array for the pattern AAAAA.
- Search for a pattern in a text containing repeated characters.
- Compare the execution time of KMP and Naive Pattern Matching.
- Explain how KMP handles a mismatch without moving the text pointer backward.
15. Interview Questions
- What is the KMP Algorithm?
- Why is KMP better than Naive Pattern Matching in the worst case?
- What does LPS stand for?
- What is a proper prefix?
- What is the difference between a prefix and a suffix?
- How is the LPS array constructed?
- Why is the first LPS value always zero?
- What happens when a mismatch occurs in KMP?
- Why does KMP not move the text pointer backward?
- What is the time complexity of building the LPS array?
- What is the total time complexity of KMP?
- Can KMP find overlapping occurrences?
- What is the space complexity of KMP?
- What is the role of lps[j - 1] during pattern searching?
16. Summary
The Knuth-Morris-Pratt Algorithm is an efficient pattern matching algorithm that avoids repeated comparisons by using information from the pattern. It builds an LPS array and uses that array to decide how to continue searching after a mismatch.
In this topic, we learned:
- What the KMP Algorithm is and why it is useful.
- What prefixes, suffixes, and proper prefixes mean.
- How to construct the LPS array.
- How KMP searches for a pattern in a text.
- How to implement KMP in C++.
- How to find overlapping pattern occurrences.
- Time complexity O(n + m) and auxiliary space O(m).