Update appNew update is available. Click here to update.
Last Updated: 15 Mar, 2021
Rearranging String
Moderate
Problem statement

You have been given two strings β€˜S’ and β€˜W’. You need to rearrange β€˜S' to obtain β€˜W’ using the following operations:-

    If the length of the string is greater than 1:

  • Divide the string into two non-empty strings β€˜X’ and β€˜Y’ such that β€˜S’ = β€˜X’ + β€˜Y’.
  • You can either swap two substrings or keep them in the same order, i.e., after this operation either S = β€˜X’ + β€˜Y’ or S = ’Y’ + β€˜X’.
  • Apply the first step recursively on β€˜X’ and β€˜Y’.
    • If the length of the string is 1 then stop.

    Example:
    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’.
    
    Input Format:
    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.
    
    Constraints:
    1 <= T <= 50
    1 <= N <= 20
    
    Time Limit: 1sec
    
    Approaches

    01Approach

    We will check through all the possible combinations in which β€˜S’ can be rearranged:

     

    1. We can divide the string into two substrings with lengths β€˜K’ and β€˜N - K’ and check if it is possible to form β€˜W’ after certain operations.
    2. We can write a recursive function β€˜rearrange(string β€˜S’, string β€˜W’)’ which returns true if it is possible to rearrange β€˜S’ to form β€˜W’.
    3. We will iterate over all possible ways in which we can break string β€˜S’ into β€˜X’ and β€˜Y’:-
      • If β€˜S’ is equal to β€˜W’ we will stop and return true.
      • If β€˜S’ is not equal to β€˜W’ and the length of β€˜S’ is β€˜1’ return false.
      • We will try both combinations:
        • If both β€˜rearrange(S[0, i - 1], W[0, i - 1])’ and β€˜rearrange(S[i, N - 1], W[i, N - 1])’ return true, then we return true.
        • If both β€˜rearrange(S[0, i - 1], W[N - i, N - 1])’ and β€˜rearrange(S[i, N - 1], W[0, N - i -1])’ return true, then we return true.
    4. If none of the above combinations return true then return false.