You’re given a string S of length N and a string P of length M. Your task is to find the number of occurrences of P in S in linear time.
For example:If S = "ababa", and P = "ab", then "ab" occurs twice in "ababa".
Note:
The string only consists of lowercase English alphabets.
The first line of input contains T, the number of test cases.
The first line of each test case contains two integers N and M, the length of string S and P respectively.
The second line of each test case contains the string S.
The third line of each test case contains the string P.
Output Format:
The only line of output of each test case should contain an integer denoting the number of occurrences of P in S.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N, M <= 10^4
Time Limit: 1 sec
2
5 2
ababa
ab
4 10
codercodes
code
2
2
In the 1st testcase,
"ab" occurs two times in "ababa". The first occurrence is from position 1 to position 2 and the second occurrence is from position 4 to position 5.
In the 2nd testcase,
"code" occurs two times in "codercodes". The first occurrence is from position 1 to position 4 and the second occurrence is from position 6 to position 9.
2
7 3
aababba
aba
6 2
zzzzyz
zz
1
3
Brute Force
A basic approach is to check all substrings of string ‘S’ and see if that substring is equal to ‘P’ or not. Let’s see how we’ll do this.
For example- String S = ababa and String P = ab
Here N = 5 and M = 2
O(N * M), where ‘N' and ‘M’ are the lengths of String ‘S’ and ‘P’ respectively.
As for every index we’re checking if there is a substring that is equal to ‘P’ or not, hence we’re using nested loops for that. The outer loop runs from 0 to “N - M” and the inner loop runs from 0 to ‘M’.
O(1)
Since we are using constant extra memory