CPS Final Project
CPS Final Project
TEAM MEMBERS:
S.PREETHA(RA2111026040015)
S.GOWRI SHANKARI(RA2111026040081)
S.VARSHAA(RA2111026040099)
PROBLEM DESCRIPTION:
Implement and compare two pattern matching algorithms: the Knuth-Morris-Pratt (KMP)
algorithm and a naive search algorithm.
KNUTH-MORRIS-PRATT (KMP) :
The KMP algorithm preprocesses the pattern to build a failure function table (also known as the
longest prefix suffix or LPS array. It then efficiently searches for the pattern within the text by
The compute LPS function calculates the LPS array for a given pattern. The KMP Search function
NAIVE SEARCH :
The Naive Search Algorithm iterates through the text character by character, checking if the pattern
matches the substring starting from each position. At each position, it compares the characters of the
If a mismatch occurs at any point, it moves to the next position in the text. If the entire pattern
m atch es th e su b strin g , it reco rd s th e startin g in d ex o f th e m atch . T h is p ro cess rep eats u n til all
p o ssib le startin g p o sitio n s in th e tex t h av e b een ch eck ed . N aiv e search h as a tim e co m p lex ity o f
O((n - m + 1) * m), where n is the length of the text and m is the length of the pattern.
PYTHON CODE:
def build_failure_table(pattern):
table = [0] * len(pattern)
i, j = 0, 1
while j < len(pattern):
if pattern[i] == pattern[j]:
table[j] = i + 1
i += 1
j += 1
elif i > 0:
i = table[i - 1]
else:
j += 1
return table
def kmp_search(text, pattern):
"""Search for a pattern in the text using the KMP algorithm."""
table = build_failure_table(pattern)
matches = []
i, j = 0, 0
while i < len(text):
if text[i] == pattern[j]:
if j == len(pattern) - 1:
matches.append(i - j)
j = table[j]
else:
i += 1
j += 1
elif j > 0:
j = table[j - 1]
else:
i += 1
return matches
# KMP Algorithm
print("\nKMP Algorithm:")
kmp_matches = kmp_search(text, pattern)
print("Matches found at indices:", kmp_matches)
OUTPUT:
KMP Algorithm:
Naive Search: