87. Scramble String LeetCode Solution

In this guide, you will get 87. Scramble String LeetCode Solution with the best time and space complexity. The solution to Scramble String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Scramble String solution in C++
  4. Scramble String solution in Java
  5. Scramble String solution in Python
  6. Additional Resources
87. Scramble StringLeetCode Solution image

Problem Statement of Scramble String

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.

See also  859. Buddy Strings LeetCode Solution

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.

Complexity Analysis

  • Time Complexity: O(n^4)
  • Space Complexity: O(n^2)

87. Scramble String LeetCode Solution in C++

class Solution {
 public:
  bool isScramble(string s1, string s2) {
    if (s1 == s2)
      return true;
    const string hashKey = s1 + '+' + s2;
    if (const auto it = mem.find(hashKey); it != mem.cend())
      return it->second;

    vector<int> count(128);

    for (int i = 0; i < s1.length(); ++i) {
      ++count[s1[i]];
      --count[s2[i]];
    }

    if (ranges::any_of(count, [](int c) { return c != 0; }))
      return mem[hashKey] = false;

    for (int i = 1; i < s1.length(); ++i) {
      if (isScramble(s1.substr(0, i), s2.substr(0, i)) &&
          isScramble(s1.substr(i), s2.substr(i)))
        return mem[hashKey] = true;
      if (isScramble(s1.substr(0, i), s2.substr(s2.length() - i)) &&
          isScramble(s1.substr(i), s2.substr(0, s2.length() - i)))
        return mem[hashKey] = true;
    }

    return mem[hashKey] = false;
  }

 private:
  unordered_map<string, bool> mem;
};
/* code provided by PROGIEZ */

87. Scramble String LeetCode Solution in Java

class Solution {
  public boolean isScramble(String s1, String s2) {
    if (s1.equals(s2))
      return true;
    final String hashKey = s1 + "+" + s2;
    if (mem.containsKey(hashKey))
      return mem.get(hashKey);

    int[] count = new int[128];

    for (int i = 0; i < s1.length(); ++i) {
      ++count[s1.charAt(i)];
      --count[s2.charAt(i)];
    }

    for (final int freq : count)
      if (freq != 0) {
        mem.put(hashKey, false);
        return false;
      }

    for (int i = 1; i < s1.length(); ++i) {
      if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&
          isScramble(s1.substring(i), s2.substring(i))) {
        mem.put(hashKey, true);
        return true;
      }
      if (isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) &&
          isScramble(s1.substring(i), s2.substring(0, s2.length() - i))) {
        mem.put(hashKey, true);
        return true;
      }
    }

    mem.put(hashKey, false);
    return false;
  }

  private Map<String, Boolean> mem = new HashMap<>();
}
// code provided by PROGIEZ

87. Scramble String LeetCode Solution in Python

class Solution:
  @functools.lru_cache(None)
  def isScramble(self, s1: str, s2: str) -> bool:
    if s1 == s2:
      return True
    if collections.Counter(s1) != collections.Counter(s2):
      return False

    for i in range(1, len(s1)):
      if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):
        return True
      if (self.isScramble(s1[:i], s2[len(s2) - i:]) and
              self.isScramble(s1[i:], s2[: len(s2) - i])):
        return True

    return False
 # code by PROGIEZ

Additional Resources

See also  513. Find Bottom Left Tree Value LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.