Knuth-Morris-Pratt (KMP) Algorithm
Problem Statementβ
Problem Descriptionβ
The Knuth-Morris-Pratt (KMP) algorithm is an efficient string searching algorithm that improves the performance of substring searches within a main string. The algorithm preprocesses the pattern to create a partial match table (also known as the "lps" array), which is used to skip unnecessary comparisons during the search process.
Examplesβ
Example 1:
Input:
Text: "abxabcabcaby"
Pattern: "abcaby"
Output:
Pattern found at index 6
Constraintsβ
- The length of the text and the pattern can be up to 10^5.
Solution of Given Problemβ
Intuition and Approachβ
The KMP algorithm follows these steps:
- Preprocessing the Pattern: Compute the longest proper prefix which is also a suffix (lps) array.
- Searching the Text: Use the lps array to skip characters in the text while matching the pattern.
Approachesβ
Codes in Different Languagesβ
- C++
#include <bits/stdc++.h>
using namespace std;
void computeLPSArray(string& pat, int M, vector<int>& lps) {
int length = 0;
lps[0] = 0;
int i = 1;
while (i < M) {
if (pat[i] == pat[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(string& pat, string& txt) {
int M = pat.length();
int N = txt.length();
vector<int> lps(M);
computeLPSArray(pat, M, lps);
int i = 0;
int j = 0;
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
cout << "Pattern found at index " << i - j << "\n";
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}
int main() {
string txt, pat;
cout << "Enter the text: ";
cin >> txt;
cout << "Enter the pattern: ";
cin >> pat;
KMPSearch(pat, txt);
return 0;
}
Complexity Analysisβ
- Time Complexity: where N is the length of the text and M is the length of the pattern.
- Space Complexity: for the lps array.
Video Explanation of Given Problemβ
Authors:
Loading...