DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Scramble String

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.

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:

class Solution:
    def isPos(self, s1, s2, a, b, c, d):
        n = b - a
        if n == 1:
            if s1[a] == s2[c]:
                return True
            else:
                return False
        key = (a, b, c, d)
        if key in self.cache:
            return self.cache[key]
        for l in range(1, n):
            r = n - l
            if self.isPos(s1, s2, a, a + l, c, c + l) and self.isPos(s1, s2, a + l, b, d - r, d):
                self.cache[key] = True
                return True
            if self.isPos(s1, s2, a, a + l, d - l, d) and self.isPos(s1, s2, a + l, b, c, c + r):
                self.cache[key] = True
                return True
        self.cache[key] = False
        return False

    def isScramble(self, s1: str, s2: str) -> bool:
        n = len(s1)
        self.cache = {}
        return self.isPos(s1, s2, 0, n, 0, n)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)