Professional Documents
Culture Documents
DAA Exp - 3.3
DAA Exp - 3.3
Experiment-3.3
1. Aim: Develop a program and analyze complexity to find all occurrences of a pattern P in a
given string S.
2. Algorithms:
Step 1: Initialize an empty list occurrences to store the starting positions of pattern P in S.
Step 2: Determine the length of the input string S as N and the length of the pattern P as M.
Step 3: Iterate over the characters of S from left to right, treating each character as a potential
starting point for pattern matching.
Step 5: Continue this process until the entire string S has been examined.
Step 6: Return the occurrences list, which contains the starting positions of all occurrences of
pattern P in S.
End of Algorithm.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
3. Code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
if (j == M) {
// Pattern 'P' found starting at position 'i'
occurrences.push_back(i);
}
}
return occurrences;
}
int main() {
string S = "ababcababcabc";
string P = "abc";
vector<int> result = findAllOccurrences(S, P);
if (result.empty()) {
cout << "Pattern not found in the string." << endl;
} else {
cout << "Pattern found at positions: ";
for (int pos : result) {
cout << pos << " ";
}
cout << endl;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
return 0;
}
3. Output:
4. Time complexity:
O((N-M+1) * M), where:
N is the length of the string S.
M is the length of the pattern P.