Experiment 9 DAA
Experiment 9 DAA
Experiment 9
Student Name: Sagandeep Singh UID: 22BCS14568
Branch: BE-CSE Section/Group: 22BCS_IOT-618/A
Semester: 5th Date of Performance:
Subject Name: Design and Analysis of Algorithms (DAA)
Subject Code:22CSH-311
lps[0] = 0;
while (i < m) {
if (P[i] == P[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
buildLPS(P, lps);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
int i = 0;
int j = 0;
bool found = false;
cout << "Searching for pattern: \"" << P << "\" in string: \"" << S << "\"\n";
cout << "--------------------------------------------\n";
while (i < n) {
if (P[j] == S[i]) {
i++;
j++;
}
if (j == m) {
found = true;
cout << ">> Pattern found at index: " << (i - j) << " <<\n";
j = lps[j - 1];
} else if (i < n && P[j] != S[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (!found) {
cout << ">> No occurrences of the pattern found. <<\n";
}
int main() {
string S = "abcxsaganxyzsagansaganwsaganpqrsagan";
string P = "sagan";
search(S, P);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
return 0;
}
5. Output
6. Time Complexity
The overall time complexity is: O(n + m)
Space Complexity:
The overall space complexity is: O(m).
7. Learning Outcome
1. . Efficient String Matching:
You will understand how the KMP algorithm efficiently finds all
occurrences of a pattern P in a string S, avoiding redundant comparisons.
2. LPS Array Utility:
You will learn how to construct and utilize the Longest Prefix
Suffix (LPS) array to skip unnecessary comparisons, optimizing the
search process.
3. Time and Space Trade-offs:
You will gain insight into analyzing algorithms for both time and
space complexity, understanding why KMP achieves linear time
complexity O(n + m) with only O(m) space overhead..
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING