101 Logo
onenoughtone

Problem Statement

Scramble String

You are developing a word puzzle game where players rearrange letters to form words. In one particular challenge, players need to determine if one string can be formed by scrambling another string in a specific way.

A string can be scrambled by splitting it into two non-empty substrings and then potentially swapping these substrings. This process can be applied recursively to each substring.

For example, if we start with "great":

  • We can split it as "g" and "reat"
  • We can then split "reat" as "r" and "eat"
  • We can swap "r" and "eat" to get "eatr"
  • So "great" can be scrambled to form "geatr"

Write a function that takes two strings s1 and s2 and returns true if s2 is a scrambled string of s1, otherwise returns false.

Examples

Example 1:

Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: We can split 'great' as 'g' + 'reat', and then 'reat' as 're' + 'at'. By swapping 're' and 'at', we get 'g' + 'at' + 're' = 'gatre', which is a scramble of 'great'.

Example 2:

Input: s1 = "abcde", s2 = "caebd"
Output: false
Explanation: No matter how we split and swap 'abcde', we cannot form 'caebd'.

Example 3:

Input: s1 = "a", s2 = "a"
Output: true
Explanation: Both strings are the same, so s2 is a scramble of s1.

Constraints

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

Problem Breakdown

To solve this problem, we need to:

  1. If two strings are scrambles of each other, they must contain the same characters with the same frequencies.
  2. The problem can be solved recursively by checking if substrings are scrambles of each other.
  3. Memoization can significantly improve the performance of the recursive solution.
  4. The problem exhibits overlapping subproblems, making it suitable for dynamic programming.
ProblemSolutionCode
101 Logo
onenoughtone