87. Scramble String

Hard

Problem Description

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:
    • 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.

Examples

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
Jump to Solution: Python Java C++ JavaScript C#

Python Solution


def isScramble(s1: str, s2: str) -> bool:
    @lru_cache(None)
    def dp(i1: int, i2: int, length: int) -> bool:
        # Base case: single character
        if length == 1:
            return s1[i1] == s2[i2]
        
        # Check if characters match in some order
        if sorted(s1[i1:i1+length]) != sorted(s2[i2:i2+length]):
            return False
        
        # Try all possible splits
        for i in range(1, length):
            # No swap
            if (dp(i1, i2, i) and 
                dp(i1+i, i2+i, length-i)):
                return True
            
            # With swap
            if (dp(i1, i2+length-i, i) and 
                dp(i1+i, i2, length-i)):
                return True
        
        return False
    
    if len(s1) != len(s2):
        return False
    
    return dp(0, 0, len(s1))

Java Solution


class Solution {
    private String s1, s2;
    private Boolean[][][] memo;
    
    public boolean isScramble(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        
        this.s1 = s1;
        this.s2 = s2;
        int n = s1.length();
        memo = new Boolean[n][n][n+1];
        
        return dp(0, 0, n);
    }
    
    private boolean dp(int i1, int i2, int length) {
        if (length == 1) {
            return s1.charAt(i1) == s2.charAt(i2);
        }
        
        if (memo[i1][i2][length] != null) {
            return memo[i1][i2][length];
        }
        
        // Check if characters match in some order
        int[] count = new int[26];
        for (int i = 0; i < length; i++) {
            count[s1.charAt(i1 + i) - 'a']++;
            count[s2.charAt(i2 + i) - 'a']--;
        }
        for (int c : count) {
            if (c != 0) {
                memo[i1][i2][length] = false;
                return false;
            }
        }
        
        // Try all possible splits
        for (int i = 1; i < length; i++) {
            // No swap
            if (dp(i1, i2, i) && dp(i1+i, i2+i, length-i)) {
                memo[i1][i2][length] = true;
                return true;
            }
            
            // With swap
            if (dp(i1, i2+length-i, i) && dp(i1+i, i2, length-i)) {
                memo[i1][i2][length] = true;
                return true;
            }
        }
        
        memo[i1][i2][length] = false;
        return false;
    }
}

C++ Solution


class Solution {
private:
    string s1, s2;
    vector>> memo;
    
    bool dp(int i1, int i2, int length) {
        if (length == 1) {
            return s1[i1] == s2[i2];
        }
        
        if (memo[i1][i2][length] != -1) {
            return memo[i1][i2][length];
        }
        
        // Check if characters match in some order
        vector count(26, 0);
        for (int i = 0; i < length; i++) {
            count[s1[i1 + i] - 'a']++;
            count[s2[i2 + i] - 'a']--;
        }
        for (int c : count) {
            if (c != 0) {
                memo[i1][i2][length] = 0;
                return false;
            }
        }
        
        // Try all possible splits
        for (int i = 1; i < length; i++) {
            // No swap
            if (dp(i1, i2, i) && dp(i1+i, i2+i, length-i)) {
                memo[i1][i2][length] = 1;
                return true;
            }
            
            // With swap
            if (dp(i1, i2+length-i, i) && dp(i1+i, i2, length-i)) {
                memo[i1][i2][length] = 1;
                return true;
            }
        }
        
        memo[i1][i2][length] = 0;
        return false;
    }
    
public:
    bool isScramble(string s1, string s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        
        this->s1 = s1;
        this->s2 = s2;
        int n = s1.length();
        memo = vector>>(n, vector>(n, vector(n+1, -1)));
        
        return dp(0, 0, n);
    }
};

JavaScript Solution


/**
 * @param {string} s1
 * @param {string} s2
 * @return {boolean}
 */
var isScramble = function(s1, s2) {
    if (s1.length !== s2.length) {
        return false;
    }
    
    const n = s1.length;
    const memo = new Map();
    
    const dp = (i1, i2, length) => {
        if (length === 1) {
            return s1[i1] === s2[i2];
        }
        
        const key = `${i1},${i2},${length}`;
        if (memo.has(key)) {
            return memo.get(key);
        }
        
        // Check if characters match in some order
        const count = new Array(26).fill(0);
        for (let i = 0; i < length; i++) {
            count[s1.charCodeAt(i1 + i) - 97]++;
            count[s2.charCodeAt(i2 + i) - 97]--;
        }
        if (count.some(c => c !== 0)) {
            memo.set(key, false);
            return false;
        }
        
        // Try all possible splits
        for (let i = 1; i < length; i++) {
            // No swap
            if (dp(i1, i2, i) && dp(i1+i, i2+i, length-i)) {
                memo.set(key, true);
                return true;
            }
            
            // With swap
            if (dp(i1, i2+length-i, i) && dp(i1+i, i2, length-i)) {
                memo.set(key, true);
                return true;
            }
        }
        
        memo.set(key, false);
        return false;
    };
    
    return dp(0, 0, n);
};

C# Solution


public class Solution {
    private string s1, s2;
    private bool?[,,] memo;
    
    public bool IsScramble(string s1, string s2) {
        if (s1.Length != s2.Length) {
            return false;
        }
        
        this.s1 = s1;
        this.s2 = s2;
        int n = s1.Length;
        memo = new bool?[n,n,n+1];
        
        return Dp(0, 0, n);
    }
    
    private bool Dp(int i1, int i2, int length) {
        if (length == 1) {
            return s1[i1] == s2[i2];
        }
        
        if (memo[i1,i2,length].HasValue) {
            return memo[i1,i2,length].Value;
        }
        
        // Check if characters match in some order
        int[] count = new int[26];
        for (int i = 0; i < length; i++) {
            count[s1[i1 + i] - 'a']++;
            count[s2[i2 + i] - 'a']--;
        }
        foreach (int c in count) {
            if (c != 0) {
                memo[i1,i2,length] = false;
                return false;
            }
        }
        
        // Try all possible splits
        for (int i = 1; i < length; i++) {
            // No swap
            if (Dp(i1, i2, i) && Dp(i1+i, i2+i, length-i)) {
                memo[i1,i2,length] = true;
                return true;
            }
            
            // With swap
            if (Dp(i1, i2+length-i, i) && Dp(i1+i, i2, length-i)) {
                memo[i1,i2,length] = true;
                return true;
            }
        }
        
        memo[i1,i2,length] = false;
        return false;
    }
}

Complexity Analysis

Solution Explanation

This solution uses dynamic programming with memoization:

Key points: