Leetcode Scramble String problem solution

In the Leetcode Scramble String problem solution, We can scramble a string s to get a string t using the following algorithm:

If the length of the string is 1, stop.
If the length of the string is > 1, do the following:
Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.
Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
Apply step 1 recursively on each of the two substrings x and y.
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 random 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 one possible scenario led s1 to be scrambled to s2, we return true.

Example 2:

Input: s1 = “abcde”, s2 = “caebd”
Output: false

Example 3:

Input: s1 = “a”, s2 = “a”
Output: true

Constraints:

  • s1.length == s2.length
  • 1 <= s1.length <= 30
  • s1 and s2 consist of lowercase English letters.

Solution in C++ Programming

class Solution {
public:
    map<pair<string,string>,bool> dp;
    bool ok(string s1,string s2){ //  to check anagram
        vector<int> dp(26);
        for(auto& c:s1)
            dp[c-'a']++;
        for(auto& c:s2)
            dp[c-'a']--;
        for(auto& c:dp){
            if(c!=0)
                return false;
        }
        return true;
    }
    // dynamic programming with memoization
    bool solve(string s1,string s2){
        int n = s1.length();
        if(n==1)
            return dp[{s1,s2}] = s1==s2;
        if(dp.count({s1,s2}))
            return dp[{s1,s2}];
        for(int i=0;i<n-1;i++){
            string f1 = s1.substr(0,i+1);
            string f2 = s1.substr(i+1);
            string f3 = s2.substr(0,i+1);
            string f4 = s2.substr(i+1);
            string f5 = s2.substr(n-i-1);
            string f6 = s2.substr(0,n-i-1);
            if(ok(f1,f3) and ok(f2,f4) and solve(f1,f3) and solve(f2,f4))
                return true;
            if(ok(f1,f5) and ok(f2,f6) and solve(f1,f5) and solve(f2,f6))
                return true;
        }
        return dp[{s1,s2}] = false;
    }
    bool isScramble(string s1, string s2) {
        return solve(s1,s2);
    }
};

Solution in Java Programming

class Solution {
    
    HashMap<String , Boolean> map = new HashMap<>();
    
    public boolean isScramble(String s1, String s2) 
    {        
        if(s1.length() != s2.length())
            return false;
        
       return solve(s1,s2);
    }
    
    private boolean solve( String a , String b)
    {
        if(a.equals(b))
            return true;
        
        if(a.length() <= 1)
            return false;
        
        String key = a + "_" + b;
        
        if(map.containsKey(key))
            return map.get(key);
        
        boolean flag = false;
        int n = a.length();
        
        for(int i=1; i<n; i++)
        {
        //comparing part1 of string a with part2 of string b and part2 of string a with part1 of string b.
           boolean on_swapping = solve(a.substring(0,i), b.substring(n-i)) &&
                           solve(a.substring(i), b.substring(0,n-i));
                           
      //comparing part1 of string a with part1 of string b and part2 of string a with part2 of string b.       
           boolean not_swapping = solve(a.substring(0,i), b.substring(0,i)) &&
                             solve(a.substring(i), b.substring(i));
            
            if(on_swapping || not_swapping)
            {
                flag = true;
                break;
            }
        }
        
        map.put(key, flag);
        
        return flag;   
    }
}

Solution in Python Programming

class Solution:
    # @param {string} s1
    # @param {string} s2
    # @return {boolean}    
    def isScramble(self,s1,s2):
        if s1==s2:
            return True
        
        result=False
        for i in range(1,len(s1)):
            if sorted(s1[:i])==sorted(s2[:i]) and sorted(s1[i:])==sorted(s2[i:]):
                result=result or ((self.isScramble(s1[:i],s2[:i])) and (self.isScramble(s1[i:],s2[i:])))
                
            if sorted(s1[:i])==sorted(s2[-i:]) and sorted(s1[i:])==sorted(s2[:-i]):
                result=result or ((self.isScramble(s1[:i],s2[-i:])) and (self.isScramble(s1[i:],s2[:-i])))
        return result

Solution in C# Programming

public class Solution {
    public bool IsScramble(string s1, string s2) {
        int N = s1.Length;
            
            if (N == 1) return s1 == s2;

            if (s1 == s2) return true;

            for (int i = 0; i < N-1; i++)
            {
                string s1l = s1.Substring(0, i + 1), s1r = s1.Substring(i + 1);
                string s2l = s2.Substring(0, i + 1), s2r = s2.Substring(i + 1);

                if (cmp(s1l, s2l) && cmp(s1r, s2r))
                {
                    if (IsScramble(s1l, s2l) && IsScramble(s1r, s2r))
                        return true;
                }

                s2r = s2.Substring(N - i - 1); s2l = s2.Substring(0, N - i-1);

                if (cmp(s1l, s2r) && cmp(s1r, s2l))
                {
                    if (IsScramble(s1l, s2r) && IsScramble(s1r, s2l))
                        return true;
                }
            }
            return false;
    }
    
    public bool cmp(string s1, string s2)
    {
        char[] a = s1.ToCharArray(), b = s2.ToCharArray();
        Array.Sort(a); Array.Sort(b);
        s1 = new String(a); s2 = new String(b);
        return s1 == s2;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *