A = “bc”, B = “abcddbc”.
String “A” is present at index 1, and 5(0-based index), but we will return 1 as it is the first occurrence of “A” in string “B”.
Can you solve this in linear time and space complexity?
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.
The first and only line of each test case contains two strings A and B, separated by a single space.
For each test case, print the index of the first occurrence of A in B, if string A is not present in string B then print -1.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= |A|, |B| <= 5 * 10^4
Time limit: 1 second
In the brute force approach, for each index of the string B, we check for the next M characters, and whenever we find a mismatch, we move one index ahead in string B. By doing this, we may have to check for the same characters again and again and the time complexity increases to O(N * M) in the worst case, where M and N are the lengths of strings A and B respectively.
However, by using the KMP algorithm, we precompute the LPS(Longest Proper Prefix that is also a Suffix) array of length M. So, we already know some of the characters in the next window. In this way, we avoid checking the same matching characters again and again.
For calculating the lps array: