You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment-3.3

Student Name: Varun Pratap UID: 21BCS9015


Branch: CSE Section/Group: IOT_636-A
Semester: 5th Date of Performance:30/10/23
Subject Name: DAA Lab Subject Code: 21CSP-314

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 4: For each character position i in S, follow these steps:


a. Initialize a variable j to 0 to represent the index within the pattern P.
b. While j is less than M and S[i + j] matches P[j], increment j.
c. If j becomes equal to M, it indicates that the pattern P is found starting at position i in S.
d. Add the index i to the occurrences list.

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.

3. Code:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<int> findAllOccurrences(const string& S, const string& P) {


vector<int> occurrences;
int N = S.size();
int M = P.size();

for (int i = 0; i <= N - M; i++) {


int j;

// Check for a pattern match starting at position i


for (j = 0; j < M; j++) {
if (S[i + j] != P[j])
break;
}

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.

You might also like