![]() |
VOOZH | about |
Given two strings A and B of equal size. Two strings are equivalent either of the following conditions hold true:
1) They both are equal. Or,
2) If we divide the string A into two contiguous substrings of same size A1 and A2 and string B into two contiguous substrings of same size B1 and B2, then one of the following should be correct:
Check whether given strings are equivalent or not. Print YES or NO.
Examples:
Input : A = "aaba", B = "abaa"
Output : YES
Explanation : Since condition 1 doesn't hold true, we can divide string A into "aaba" = "aa" + "ba" and string B into "abaa" = "ab" + "aa". Here, 2nd subcondition holds true where A1 is equal to B2 and A2 is recursively equal to B1
Input : A = "aabb", B = "abab"
Output : NO
Naive Solution : A simple solution is to consider all possible scenarios. Check first if the both strings are equal return "YES", otherwise divide the strings and check if A1 = B1 and A2 = B2 or A1 = B2 and A2 = B1 by using four recursive calls. Complexity of this solution would be O(n2), where n is the size of the string.
Algorithm
is_recursive_equiv(A, B):
if A == B:
return "YES" // base case: A and B are already equivalent
if length(A) is odd or length(B) is odd:
return "NO" // base case: odd-length strings cannot be recursively equivalent
n = length(A)
A1 = substring(A, 0, n/2) // divide A into two halves
A2 = substring(A, n/2)
B1 = substring(B, 0, n/2) // divide B into two halves
B2 = substring(B, n/2)
if (is_recursive_equiv(A1, B1) == "YES" and is_recursive_equiv(A2, B2) == "YES") or
(is_recursive_equiv(A1, B2) == "YES" and is_recursive_equiv(A2, B1) == "YES"):
return "YES" // if corresponding halves are recursively equivalent, return "YES"
return "NO" // otherwise, return "NO"
Implementation of above approach
YES NO
Efficient Solution : Let's define following operation on string S. We can divide it into two halves and if we want we can swap them. And also, we can recursively apply this operation to both of its halves. By careful observation, we can see that if after applying the operation on some string A, we can obtain B, then after applying the operation on B we can obtain A. And for the given two strings, we can recursively find the least lexicographically string that can be obtained from them. Those obtained strings if are equal, answer is YES, otherwise NO. For example, least lexicographically string for "aaba" is "aaab". And least lexicographically string for "abaa" is also "aaab". Hence both of these are equivalent.
Steps to follow to implement the above approach:
Below is the code to implement the above approach:
YES NO
Time Complexity: O(N*logN), where N is the size of the string.
Auxiliary Space: O(logN)