Algorithms and Adv.
Data Structures
Practical 6
Priyanka Lakra
CSC/22/47
Write a program to search a pattern in a given text using the KMP algorithm.
#include<iostream>
#include<vector>
#include<string>
using namespace std;
vector<int> KMPFailureFunction(const string& Pattern) {
int m = Pattern.size();
vector<int> f(m, 0);
int j = 0;
for (int i = 1; i < m; i++) {
while (j > 0 && Pattern[j] != Pattern[i]) {
j = f[j - 1];
if (Pattern[j] == Pattern[i]) {
j++;
f[i] = j;
return f;
int KMPMatch(const string& Text, const string& Pattern) {
int n = Text.size();
int m = Pattern.size();
vector<int> f = KMPFailureFunction(Pattern);
int i = 0, j = 0;
while (i < n) {
if (Pattern[j] == Text[i]) {
if (j == m - 1) {
return i - m + 1;
i++;
j++;
} else if (j > 0) {
j = f[j - 1];
} else {
i++;
return -1;
int main() {
string text;/* = "abxabcabcaby";*/
cout<<"Enter the text: ";
cin>>text;
cout<<endl;
string pattern;/* = "abcaby";*/
cout<<"Enter the string: ";
cin>>pattern;
cout<<endl;
int result = KMPMatch(text, pattern);
if (result != -1) {
cout << "Pattern found at index: " << result << endl;
} else {
cout << "There is no substring of T matching P." << endl;
return 0;