Problem Statement

We can scramble a string s to get a string t using the following algorithm:

  1. If the length of the string is 1, stop.
  2. If the length of the string is > 1, do the following:

Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.

Example 1:

Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: One possible scenario applied on s1 is:
"great" --> "gr/eat" // divide at random index.
"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at ranom index each of them.
"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
The algorithm stops now and the result string is "rgeat" which is s2.
As there is one possible scenario that led s1 to be scrambled to s2, we return true.

Problem Link

Reference Videos

https://www.youtube.com/watch?v=SqA0o-DGmEw&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=41&ab_channel=AdityaVerma

Explanation

Code

//Using Top-Down DP

class Solution {
public:
    unordered_map <string,bool> m;
    bool isScramble(string s1, string s2) {
        
        return solve(s1,s2);
    }
    
    bool solve(string s1, string s2) {
        
        if(s1.size()!=s2.size())
            return false;
        
        if(!s1.compare(s2)) // if strings are same
            return true;
        
        if(s1.size()<=1) //if string s1 is empty or if s1 contains a single character because it is already proven
            return false;// above that bothe the strings are not same
        
        string key = "";
        key = s1 + " " + s2;
       
        if(m.find(key)!=m.end())
            return m[key];
        
        bool flag = false;
        int n = s1.size();
        
        for(int i=1;i<n;i++) {
            
            bool cond1 = solve(s1.substr(0,i),s2.substr(0,i)) and solve(s1.substr(i,n-i),s2.substr(i,n-i)); //if no swap happens 
            bool cond2 = solve(s1.substr(0,i),s2.substr(n-i,i)) and solve(s1.substr(i,n-i),s2.substr(0,n-i)); // if swap happens
            
            if(cond1||cond2)
            {
                flag = true;
                break;
            }
        }
        
        return m[key] = flag;
        
    }
};
// Time Complexity : O(n^3),   Space Complexity : O(n^2)