Problem of the day
Anish is given a string S and has been asked to determine if the given string S contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
As a friend of Anish, your task is to return “True” if the string S contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order) otherwise return “False” (without quotes).
Example:-The string “ABBA” has two non-overlapping substrings “AB” and “BA” respectively. So “True” will be printed(without quotes).
The first line contains a single integer T representing the number of test cases.
The first line of each test case contains the string S denoting the given string to Anish.
Output format :
For each test case, print "True" if the string S contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order) else print "False” (without quotes).
The output of each test case should be printed in a separate line.
Note:
You are not required to print anything, it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= |S| <= 10^4
The string S contains uppercase Latin letters only.
Time Limit = 1 sec
2
ABA
BACFAB
False
True
In the first test case, there are no two non-overlapping substrings, so “False” is printed.
In the second test case, there are two non-overlapping substrings (BACFAB), so “True” is printed.
2
ABBA
AXBYBXA
True
False
Check the first and last occurrences of the sub-string “AB” and “BA”.
We can check the first occurrence of substring “AB” and the last occurrence of substring “BA”. If they don’t overlap, return True. Else, check the first occurrence of substring “BA” and the last occurrence of substring “AB”. If they don’t overlap, return True, else return False.
Algorithm:-
O(|S|), where |S| is the length of the string S.
We are iterating through every character in the string S once, so the Time complexity is O(|S|) when |S| is the length of the string S.
O(1)
Constant Space is used.