You have been given two strings ‘S’ and ‘W’. You need to rearrange ‘S' to obtain ‘W’ using the following operations:-
If ‘S’= “great” and ‘W’= “tagre”, ‘S’ can be rearranged to form ‘W’.
‘S’ = “gre” + “at” (We choose to swap ‘X’ & ‘Y’)
‘S’ = “at” + “gre”
Now letting “gre” as it is and applying operation on “at”.
‘S’ = “a” + “t” + “gre”
Swapping “a” and “t”
‘S’ = “t” + “a” + “gre”
Therefore ‘S’ can be rearranged into ‘W’.
Note:
Both strings are of the same length and operations can only be applied to string ‘S’.
The first line contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ denoting the length of the string ‘S’ and ‘W'.
The next line of the test case contains two space-separated strings ‘S’ and ‘W’.
Output Format:
For each test case print ‘True’ if ‘S’ can be rearranged to form ‘W’ else print ‘False’.
Note:
You do not need to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 50
1 <= N <= 20
Time Limit: 1sec
2
5
abcde edabc
5
great bagre
True
False
Test case 1:
We can break “abcde” into “abc” and “de”. We swap two strings now we recursively apply the operation on “abc” and “de”. Since we want “abc” to be equivalent to “abc” we can leave it as it is. We will break “de” into “d” and “e”. We swap two strings because we want them to be equivalent. Finally, we have “edabc”.
Therefore the answer is “True”.
Test case 2:
‘s’ does not contain ‘b’ whereas ‘w’ contains ‘b’. Therefore it is impossible to rearrange ‘s’ to form ‘w’.
Therefore the answer is “False”.
2
1
b b
2
ab bac
True
False
Test case 1:
The given strings are same only and therefore the answer is “True”.
Test case 2:
‘s’ does not contain ‘c’ whereas ‘w’ contains ‘c’. Therefore it is impossible to rearrange ‘s’ to form ‘w’. Therefore the answer is “False”.
Try to iterate all possible combinations.
We will check through all the possible combinations in which ‘S’ can be rearranged:
O(5^N), where ‘N’ denotes the length of the string.
As we are recursively calling each sub problem to get the answer of big problem. Each sub problem is divided into 5 subproblem and thus, overall time complexity is O(5^N).
O(N), where ‘N’ denotes the length of the string.
As we recurse a stack of size ‘N’ gets built to store strings. Thus, space complexity is O(N).