


Left shift is defined as a single circular rotation on the string after which the first character becomes the last character and all other characters are shifted one index to the left.
If A = “an”, B = “can”.
After performing one left shift operation, string B becomes “anc”.
After performing two left shift operations, string B becomes “nca”.
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 line of each test case contains the string A.
The second line of each test case contains the string B.
For each test case, print the minimum number of left shift operations required in order to obtain the longest common prefix of string A and B.
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
Where |A| and |B| denote the length of string, A and B respectively.
All the characters of the string A and B contain lowercase English letters only.
Time limit: 1 second
lengthOfTheCommonPrefix(A, B):
In the brute force approach, we perform the left shift operation N-1 number of times on the string B and find the length of the common prefix of A and B, after each left shift operation. By doing this, we may have to check for the same characters again and again and hence, the time complexity increases to O(N*(N+M) in the worst case, where M and N are the lengths of strings A and B respectively.
By observing the property of left shift operation, we get that after K left shift operations, the first K characters of string B are removed and inserted to the end of the string. And we can perform maximum N-1 left shifts because, after the Nth left shift, the string B is converted again to its original form. So, instead of performing left shift again and again, we can concatenate string B with itself. After doing so, the only task that remains is to find out the longest prefix of string A that is present in string B and the index of this longest prefix in string B, which is exactly the number of shift operations needed.
For finding the index of this longest prefix, we can use KMP algorithm in which we precompute the LPS(Longest Proper Prefix that is also a Suffix) array of length M. So, we already know some characters in the next window. In this way, we avoid checking the same matching characters again and again.
For calculating the lps array: