Daa 9 Abhi
Daa 9 Abhi
Experiment: 9
Name: Abhigyan Singh UID: 22BCS14340
Branch: CSE Section: FL_IOT-602-A
Semester: 5 Date: 13 Oct, 2024
Subject Name: DAA Lab Subject Code: 22CSH-311
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P
in a given string S.
3. Algorithm:
• Start from the first character of S and slide the pattern P over S one character at a time.
• For each position i in S where i ranges from 0 to n - m (i.e., until the remaining part of
S is smaller than P):
a. Compare the substring of S starting at position i with the pattern P.
b. For each position j in the pattern P where j ranges from 0 to m-1:
✓ If the characters S[i + j] and P[j] match, continue comparing the next characters.
✓ If any character does not match, break out of the loop and slide the pattern to the
next position.
c. If the entire pattern P matches the substring in S, record the starting index i as a match.
• Repeat this until the pattern has been compared with all possible substrings of S.
4. Implementation/Code:
#include <iostream>
#include <string>
using namespace std;
int j;
int main() {
string S, P;
cout << "Enter the string S: ";
getline(cin, S);
cout << "Enter the pattern P: ";
getline(cin, P);
findPatternOccurrences(S, P);
return 0;
}
5. Output:
6. Time Complexity:
In the worst case, the algorithm compares each character of P with each corresponding
character of S for all possible positions, resulting in a time complexity of O(n×m).
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
7. Learning Outcomes:
• Gain familiarity with one of the simplest methods of pattern matching in strings, which
serves as a foundation for more advanced algorithms.
• Learn how to compare a pattern with a substring in a larger string and recognize the sliding
window concept for pattern matching.
• Understand how the time complexity O(n×m) is derived and its implications, especially in
worst-case scenarios.
• Recognize when the Naive Pattern Matching algorithm becomes inefficient and appreciate
the need for more advanced algorithms like KMP or Boyer-Moore for larger datasets or
patterns.