Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Check if a string is a scrambled form of another string
Next article icon

Check if a string is a scrambled form of another string

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given two strings s1 and s2 of equal length, the task is to determine if s2 is a scrambled version of s1.

A scrambled string is formed by recursively splitting the string into two non-empty substrings and rearranging them randomly (s = x + y or s = y + x) and then recursively scramble the two substrings.

Note: A scrambled string is different from an anagram.

Examples:

Input: s1="coder", s2="ocder" 
Output: Yes 
Explanation: "ocder" is a scrambled form of "coder"

Input: s1="abcde", s2="caebd" 
Output: No 
Explanation: "caebd" is not a scrambled form of "abcde"

[Naive Approach]  Divide and Conquer Approach - Exponential Time

For s2[0..n-1] to be a scrambled version of s1[0..n-1], there must be an index i such that at least one of the following conditions holds true: 

  1. s2[0...i] is a scrambled version of s1[0...i], and s2[i+1...n] is a scrambled version of s1[i+1...n].
  2. s2[0...i] is a scrambled version of s1[n-i...n], and s2[i+1...n] is a scrambled version of s1[0...n-i-1].

Note: A helpful optimization step is to check if the two strings are anagrams of each other beforehand. If they are not anagrams, it means the strings contain different characters and cannot be scrambled forms of each other.

C++
// C++ Program to check if a // given string is a scrambled // form of another string #include <bits/stdc++.h> using namespace std;  bool isAnagram(string &s1, string &s2) {     vector<int> cnt(26, 0);     for (char ch: s1) cnt[ch-'a']++;     for (char ch: s2) cnt[ch-'a']--;          for (int i=0; i<26; i++) {         if (cnt[i]!=0) return false;     }     return true; }  bool isScramble(string s1, string s2) {          // Strings of non-equal length     // cant' be scramble strings     if (s1.length() != s2.length()) {         return false;     }      int n = s1.length();      // Empty strings are scramble strings     if (n == 0) {         return true;     }      // Equal strings are scramble strings     if (s1 == s2) {         return true;     }      // Check for the condition of anagram     if (isAnagram(s1, s2) == false) {         return false;     }      for (int i = 1; i < n; i++) {          // Check if s2[0...i] is a scrambled         // string of s1[0...i] and if s2[i+1...n]         // is a scrambled string of s1[i+1...n]         if (isScramble(s1.substr(0, i), s2.substr(0, i))             && isScramble(s1.substr(i, n - i),                           s2.substr(i, n - i))) {             return true;         }          // Check if s2[0...i] is a scrambled         // string of s1[n-i...n] and s2[i+1...n]         // is a scramble string of s1[0...n-i-1]         if (isScramble(s1.substr(0, i),                        s2.substr(n - i, i))             && isScramble(s1.substr(i, n - i),                           s2.substr(0, n - i))) {             return true;         }     }      // If none of the above     // conditions are satisfied     return false; }  int main() {     string s1 = "coder";     string s2 = "ocred";      if (isScramble(s1, s2)) {         cout << "Yes";     }     else {         cout << "No";     }      return 0; } 
Java
// Java Program to check if a // given string is a scrambled // form of another string  import java.util.Arrays;  class GfG {          static boolean isAnagram(String s1, String s2) {         int[] cnt = new int[26];         for (char ch : s1.toCharArray()) cnt[ch - 'a']++;         for (char ch : s2.toCharArray()) cnt[ch - 'a']--;                  for (int i = 0; i < 26; i++) {             if (cnt[i] != 0) return false;         }         return true;     }      static boolean isScramble(String s1, String s2) {                  // Strings of non-equal length         // cant' be scramble strings         if (s1.length() != s2.length()) {             return false;         }          int n = s1.length();          // Empty strings are scramble strings         if (n == 0) {             return true;         }          // Equal strings are scramble strings         if (s1.equals(s2)) {             return true;         }          // Check for the condition of anagram         if (!isAnagram(s1, s2)) {             return false;         }          for (int i = 1; i < n; i++) {              // Check if s2[0...i] is a scrambled             // string of s1[0...i] and if s2[i+1...n]             // is a scrambled string of s1[i+1...n]             if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&                 isScramble(s1.substring(i), s2.substring(i))) {                 return true;             }              // Check if s2[0...i] is a scrambled             // string of s1[n-i...n] and s2[i+1...n]             // is a scramble string of s1[0...n-i-1]             if (isScramble(s1.substring(0, i), s2.substring(n - i)) &&                 isScramble(s1.substring(i), s2.substring(0, n - i))) {                 return true;             }         }          // If none of the above         // conditions are satisfied         return false;     }      public static void main(String[] args) {         String s1 = "coder";         String s2 = "ocred";          if (isScramble(s1, s2)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python
# Python Program to check if a # given string is a scrambled # form of another string  def isAnagram(s1, s2):     cnt = [0] * 26     for ch in s1:         cnt[ord(ch) - ord('a')] += 1     for ch in s2:         cnt[ord(ch) - ord('a')] -= 1      for i in range(26):         if cnt[i] != 0:             return False     return True  def isScramble(s1, s2):          # Strings of non-equal length     # cant' be scramble strings     if len(s1) != len(s2):         return False      n = len(s1)      # Empty strings are scramble strings     if n == 0:         return True      # Equal strings are scramble strings     if s1 == s2:         return True      # Check for the condition of anagram     if not isAnagram(s1, s2):         return False      for i in range(1, n):          # Check if s2[0...i] is a scrambled         # string of s1[0...i] and if s2[i+1...n]         # is a scrambled string of s1[i+1...n]         if isScramble(s1[:i], s2[:i]) and isScramble(s1[i:], s2[i:]):             return True          # Check if s2[0...i] is a scrambled         # string of s1[n-i...n] and s2[i+1...n]         # is a scramble string of s1[0...n-i-1]         if isScramble(s1[:i], s2[n - i:]) and isScramble(s1[i:], s2[:n - i]):             return True      # If none of the above     # conditions are satisfied     return False  if __name__ == "__main__":     s1 = "coder"     s2 = "ocred"      if isScramble(s1, s2):         print("Yes")     else:         print("No") 
C#
// C# Program to check if a // given string is a scrambled // form of another string  using System;  class GfG {          static bool isAnagram(string s1, string s2) {         int[] cnt = new int[26];         foreach (char ch in s1) cnt[ch - 'a']++;         foreach (char ch in s2) cnt[ch - 'a']--;                  for (int i = 0; i < 26; i++) {             if (cnt[i] != 0) return false;         }         return true;     }      static bool isScramble(string s1, string s2) {                  // Strings of non-equal length         // cant' be scramble strings         if (s1.Length != s2.Length) {             return false;         }          int n = s1.Length;          // Empty strings are scramble strings         if (n == 0) {             return true;         }          // Equal strings are scramble strings         if (s1 == s2) {             return true;         }          // Check for the condition of anagram         if (!isAnagram(s1, s2)) {             return false;         }          for (int i = 1; i < n; i++) {              // Check if s2[0...i] is a scrambled             // string of s1[0...i] and if s2[i+1...n]             // is a scrambled string of s1[i+1...n]             if (isScramble(s1.Substring(0, i), s2.Substring(0, i)) &&                 isScramble(s1.Substring(i), s2.Substring(i))) {                 return true;             }              // Check if s2[0...i] is a scrambled             // string of s1[n-i...n] and s2[i+1...n]             // is a scramble string of s1[0...n-i-1]             if (isScramble(s1.Substring(0, i), s2.Substring(n - i)) &&                 isScramble(s1.Substring(i), s2.Substring(0, n - i))) {                 return true;             }         }          // If none of the above         // conditions are satisfied         return false;     }      static void Main() {         string s1 = "coder";         string s2 = "ocred";          if (isScramble(s1, s2)) {             Console.WriteLine("Yes");         } else {             Console.WriteLine("No");         }     } } 
JavaScript
// JavaScript Program to check if a // given string is a scrambled // form of another string  function isAnagram(s1, s2) {     let cnt = new Array(26).fill(0);     for (let ch of s1) cnt[ch.charCodeAt(0) - 'a'.charCodeAt(0)]++;     for (let ch of s2) cnt[ch.charCodeAt(0) - 'a'.charCodeAt(0)]--;      for (let i = 0; i < 26; i++) {         if (cnt[i] !== 0) return false;     }     return true; }  function isScramble(s1, s2) {          if (s1.length !== s2.length) return false;      let n = s1.length;     if (n === 0) return true;     if (s1 === s2) return true;     if (!isAnagram(s1, s2)) return false;      for (let i = 1; i < n; i++) {         if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&             isScramble(s1.substring(i), s2.substring(i))) return true;         if (isScramble(s1.substring(0, i), s2.substring(n - i)) &&             isScramble(s1.substring(i), s2.substring(0, n - i))) return true;     }      return false; }  let s1 = "coder", s2 = "ocred"; console.log(isScramble(s1, s2) ? "Yes" : "No"); 

Output
Yes

Time Complexity: O(2k+ 2(n-k)), where k and n-k are the length of the two substrings.
Auxiliary Space: O(2n), recursion stack.

[Expected Approach - 1] Using Top-Down DP (Memoization) - O(n^4) time and O(n^3) space

The idea is to use dynamic programming to memoize subproblems where substrings of s1 and s2 can be split and compared recursively under the scramble conditions. By capturing overlapping subproblems, we avoid redundant computations and improve efficiency.

State Representation:
Define dp[i1][j1][i2][j2] as true if the substring s1[i1...j1] can be scrambled into s2[i2...j2].

Recurrence Relation:
For every possible split point len (1 ≤ len < j1 - i1 + 1), check two scrambling conditions:

  1. No Swap:
    Check if the first len characters of s1[i1...j1] and s2[i2...j2] are scrambles, and the remaining characters are scrambles:
    • dp[i1][j1][i2][j2] |= dp[i1][i1+len-1][i2][i2+len-1] && dp[i1+len][j1][i2+len][j2]
  2. Swap:
    Check if the first len characters of s1[i1...j1] match the last len characters of s2[i2...j2], and vice versa:
    • dp[i1][j1][i2][j2] |= dp[i1][i1+len-1][j2-len+1][j2] && dp[i1+len][j1][i2][j2-len]

Base Case:
If i1 == j1 (substring length 1), return s1[i1] == s2[i2].

Key Insight: The end indices j1 and j2 can be derived from the start indices i1, i2, and the substring length l (since j1 = i1 + l - 1 and j2 = i2 + l - 1). This eliminates redundant parameters. Now the states can be defined as:

  • Define dp[i1][i2][l] as true if the substring starting at i1 in s1 with length l can be scrambled into the substring starting at i2 in s2 with the same length l.

Recurrence Relation:
For every possible split len (1 ≤ len < l), check:

  1. No Swap: dp[i1][i2][l] |= dp[i1][i2][len] && dp[i1+len][i2+len][l-len]
  2. Swap: dp[i1][i2][l] |= dp[i1][i2 + (l-len)][len] && dp[i1+len][i2][l-len]

Base Case:
If l == 1, return s1[i1] == s2[i2].

C++
// C++ Program to check if a // given string is a scrambled // form of another string #include <bits/stdc++.h> using namespace std;  bool scrambleRecur(int i1, int j1, int i2, int j2, string &s1, string &s2, vector<vector<vector<vector<int>>>> &dp) {          // For single character, compare     // the two characters. 	if (i1==j1) { 		return s1[i1] == s2[i2]; 	}          // If value is computed, return it. 	if (dp[i1][j1][i2][j2]!=-1) return dp[i1][j1][i2][j2];  	bool ans = false; 	int maxLen = j1-i1+1; 	 	for (int len=1; len<maxLen; len++) { 	     	    // Check if s2[i2, i2+len-1] is scrambled version of s1[i1, i1+len-1]  	    // and s2[i2+len, j2] is scrambled version of s1[i1+len, j1]. 		bool val1 = scrambleRecur(i1, i1+len-1, i2, i2+len-1, s1, s2, dp) && 		            scrambleRecur(i1+len, j1, i2+len, j2, s1, s2, dp);                  // Check if s2[j2-len+1, j2] is scrambled version of s1[i1, i1+len-1]  	    // and s2[i2, j2-len] is scrambled version of s1[i1+len, j1]. 		bool val2 = scrambleRecur(i1, i1+len-1, j2-len+1, j2, s1, s2, dp) && 		            scrambleRecur(i1+len, j1, i2, j2-len, s1, s2, dp);                  // If any version is scrambled. 		if (val1 || val2) {ans = true; break; } 	}      // Memoize the value and return it. 	return dp[i1][j1][i2][j2] = ans; }  bool isScramble(string s1, string s2) { 	int n = s1.length(); 	 	// Create a 4d array. 	vector<vector<vector<vector<int>>>> dp(n,     vector<vector<vector<int>>>(n,      vector<vector<int>>(n, vector<int>(n, -1))));      	return scrambleRecur(0, n-1, 0, n-1, s1, s2, dp); }  int main() { 	string s1 = "coder"; 	string s2 = "ocred";  	if (isScramble(s1, s2)) { 		cout << "Yes"; 	} 	else { 		cout << "No"; 	}  	return 0; } 
Java
// Java Program to check if a // given string is a scrambled // form of another string import java.util.Arrays;  class GfG {          static boolean scrambleRecur(int i1, int i2, int length,      String s1, String s2, int[][][] dp) {                  // For single character, compare         // the two characters.         if (length == 1) {             return s1.charAt(i1) == s2.charAt(i2);         }                  // If value is computed, return it.         if (dp[i1][i2][length] != -1) return dp[i1][i2][length] == 1;          boolean ans = false;          for (int len = 1; len < length; len++) {                          // Check if s2[i2, i2+len-1] is scrambled version              // of s1[i1, i1+len-1] and s2[i2+len, i2+length-1] is              // scrambled version of s1[i1+len, i1+length-1].             boolean val1 = scrambleRecur(i1, i2, len, s1, s2, dp) &&                            scrambleRecur(i1 + len, i2 + len, length - len, s1, s2, dp);                          // Check if s2[i2+length-len+1, i2+length] is scrambled version              // of s1[i1, i1+len-1] and s2[i2, i2+length-len] is scrambled              // version of s1[i1+len, i1+length-1].             boolean val2 = scrambleRecur(i1, i2 + length - len, len, s1, s2, dp) &&                            scrambleRecur(i1 + len, i2, length - len, s1, s2, dp);                          // If any version is scrambled. 		    if (val1 || val2) {ans = true; break; }         }          // Memoize the value and return it.         dp[i1][i2][length] = ans ? 1 : 0;         return ans;     }      static boolean isScramble(String s1, String s2) {         int n = s1.length();                  // Create a 3d array.         int[][][] dp = new int[n][n][n + 1];         for (int[][] arr2D : dp)             for (int[] arr1D : arr2D)                 Arrays.fill(arr1D, -1);          return scrambleRecur(0, 0, n, s1, s2, dp);     }      public static void main(String[] args) {         String s1 = "coder";         String s2 = "ocred";          if (isScramble(s1, s2)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python
# Python Program to check if a # given string is a scrambled # form of another string  def scrambleRecur(i1, i2, length, s1, s2, dp):          # For single character, compare     # the two characters.     if length == 1:         return s1[i1] == s2[i2]          # If value is computed, return it.     if dp[i1][i2][length] != -1:         return dp[i1][i2][length]      ans = False      for len_ in range(1, length):                  # Check if s2[i2, i2+len-1] is scrambled version          # of s1[i1, i1+len-1] and s2[i2+len, i2+length-1]          # is scrambled version of s1[i1+len, i1+length-1].         val1 = scrambleRecur(i1, i2, len_, s1, s2, dp) and \                scrambleRecur(i1 + len_, i2 + len_, length - len_, s1, s2, dp)                  # Check if s2[i2+length-len+1, i2+length] is scrambled          # version of s1[i1, i1+len-1] and s2[i2, i2+length-len]          # is scrambled version of s1[i1+len, i1+length-1].         val2 = scrambleRecur(i1, i2 + length - len_, len_, s1, s2, dp) and \                scrambleRecur(i1 + len_, i2, length - len_, s1, s2, dp)                  # If any version is scrambled.         if (val1 or val2):             ans = True             break      # Memoize the value and return it.     dp[i1][i2][length] = ans     return ans  def isScramble(s1, s2):     n = len(s1)          # Create a 3d array.     dp = [[[-1] * (n + 1) for _ in range(n)] for _ in range(n)]          return scrambleRecur(0, 0, n, s1, s2, dp)  if __name__ == "__main__":     s1 = "coder"     s2 = "ocred"      if isScramble(s1, s2):         print("Yes")     else:         print("No") 
C#
// C# Program to check if a // given string is a scrambled // form of another string using System;  class GfG {          static bool scrambleRecur(int i1, int i2, int length,      string s1, string s2, int[,,] dp) {                  // For single character, compare         // the two characters.         if (length == 1) {             return s1[i1] == s2[i2];         }                  // If value is computed, return it.         if (dp[i1, i2, length] != -1)              return dp[i1, i2, length] == 1;          bool ans = false;          for (int len = 1; len < length; len++) {                          // Check if s2[i2, i2+len-1] is scrambled version              // of s1[i1, i1+len-1] and s2[i2+len, i2+length-1]              // is scrambled version of s1[i1+len, i1+length-1].             bool val1 = scrambleRecur(i1, i2, len, s1, s2, dp) &&                         scrambleRecur(i1 + len, i2 + len, length - len, s1, s2, dp);                          // Check if s2[i2+length-len+1, i2+length] is scrambled              // version of s1[i1, i1+len-1] and s2[i2, i2+length-len]             // is scrambled version of s1[i1+len, i1+length-1].             bool val2 = scrambleRecur(i1, i2 + length - len, len, s1, s2, dp) &&                         scrambleRecur(i1 + len, i2, length - len, s1, s2, dp);                          // If any version is scrambled. 		    if (val1 || val2) {ans = true; break; }         }          // Memoize the value and return it.         dp[i1, i2, length] = ans ? 1 : 0;         return ans;     }      static bool isScramble(string s1, string s2) {         int n = s1.Length;                  // Create a 3d array.         int[,,] dp = new int[n, n, n + 1];         for (int i = 0; i < n; i++)             for (int j = 0; j < n; j++)                 for (int k = 0; k <= n; k++)                     dp[i, j, k] = -1;          return scrambleRecur(0, 0, n, s1, s2, dp);     }      static void Main() {         string s1 = "coder";         string s2 = "ocred";          if (isScramble(s1, s2)) {             Console.WriteLine("Yes");         } else {             Console.WriteLine("No");         }     } } 
JavaScript
// JavaScript Program to check if a // given string is a scrambled // form of another string  function scrambleRecur(i1, i2, length, s1, s2, dp) {          // For single character, compare     // the two characters.     if (length === 1) {         return s1[i1] === s2[i2];     }          // If value is computed, return it.     if (dp[i1][i2][length] !== -1) return dp[i1][i2][length];      let ans = false;          for (let len = 1; len < length; len++) {                  // Check if s2[i2, i2+len-1] is scrambled version          // of s1[i1, i1+len-1] and s2[i2+len, i2+length-1]          // is scrambled version of s1[i1+len, i1+length-1].         let val1 = scrambleRecur(i1, i2, len, s1, s2, dp) &&                    scrambleRecur(i1 + len, i2 + len, length - len, s1, s2, dp);                  // Check if s2[i2+length-len+1, i2+length] is scrambled          // version of s1[i1, i1+len-1] and s2[i2, i2+length-len]          // is scrambled version of s1[i1+len, i1+length-1].         let val2 = scrambleRecur(i1, i2 + length - len, len, s1, s2, dp) &&                    scrambleRecur(i1 + len, i2, length - len, s1, s2, dp);                  // If any version is scrambled. 		if (val1 || val2) {ans = true; break; }     }      // Memoize the value and return it.     return dp[i1][i2][length] = ans; }  function isScramble(s1, s2) {     let n = s1.length;          // Create a 3D array.     let dp = new Array(n).fill(0).map(() =>          new Array(n).fill(0).map(() =>              new Array(n + 1).fill(-1)         )     );          return scrambleRecur(0, 0, n, s1, s2, dp); }  let s1 = "coder"; let s2 = "ocred";  if (isScramble(s1, s2)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes

Time Complexity: O(n^4), where n is the length of the given strings.
Auxiliary Space: O(n^3), due to memoization.

[Expected Approach - 2] Using Bottom-Up DP and Space Optimization - O(n^4) time and O(n^3) space

The idea is to fill the dp table from bottom to up. The table is filled in an iterative manner from len = 2 to n, i1 = 0 to n-1 and i2 = 0 to n-1.

Instead of maintaining 4 parameters (i1, j1, i2, j2), we maintain 3 parameters (i1, i2, len) as j1 - i1 is same as j2 - i2.

C++
// C++ Program to check if a // given string is a scrambled // form of another string #include <bits/stdc++.h> using namespace std;  bool isScramble(string s1, string s2) {     int n = s1.length();          // dp[i1][i2][l] indicates whether      // s1.substr(i1, l) can scramble into s2.substr(i2, l)     vector<vector<vector<bool>>> dp(n,      vector<vector<bool>>(n, vector<bool>(n + 1, false)));          // Base case: substrings of length 1     for (int i1 = 0; i1 < n; ++i1) {         for (int i2 = 0; i2 < n; ++i2) {             dp[i1][i2][1] = (s1[i1] == s2[i2]);         }     }          // Fill DP table for lengths from 2 to n     for (int l = 2; l <= n; ++l) {         for (int i1 = 0; i1 <= n - l; ++i1) {             for (int i2 = 0; i2 <= n - l; ++i2) {                 for (int len = 1; len < l; ++len) {                                          // Case 1: No swap                     bool noSwap = dp[i1][i2][len] &&                      dp[i1 + len][i2 + len][l - len];                                          // Case 2: Swap                     bool swap = dp[i1][i2 + (l - len)][len] &&                      dp[i1 + len][i2][l - len];                     if (noSwap || swap) {                         dp[i1][i2][l] = true;                         break;                     }                 }             }         }     }          return dp[0][0][n]; }  int main() {     string s1 = "coder";     string s2 = "ocred";          if (isScramble(s1, s2)) {         cout << "Yes";     } else {         cout << "No";     }          return 0; } 
Java
// Java Program to check if a // given string is a scrambled // form of another string  class GfG {          static boolean isScramble(String s1, String s2) {         int n = s1.length();                  // dp[i1][i2][l] indicates whether          // s1.substr(i1, l) can scramble into s2.substr(i2, l)         boolean[][][] dp = new boolean[n][n][n + 1];                  // Base case: substrings of length 1         for (int i1 = 0; i1 < n; ++i1) {             for (int i2 = 0; i2 < n; ++i2) {                 dp[i1][i2][1] = (s1.charAt(i1) == s2.charAt(i2));             }         }                  // Fill DP table for lengths from 2 to n         for (int l = 2; l <= n; ++l) {             for (int i1 = 0; i1 <= n - l; ++i1) {                 for (int i2 = 0; i2 <= n - l; ++i2) {                     for (int len = 1; len < l; ++len) {                                                  // Case 1: No swap                         boolean noSwap = dp[i1][i2][len] &&                          dp[i1 + len][i2 + len][l - len];                                                  // Case 2: Swap                         boolean swap = dp[i1][i2 + (l - len)][len] &&                          dp[i1 + len][i2][l - len];                         if (noSwap || swap) {                             dp[i1][i2][l] = true;                             break;                         }                     }                 }             }         }                  return dp[0][0][n];     }      public static void main(String[] args) {         String s1 = "coder";         String s2 = "ocred";                  if (isScramble(s1, s2)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python
# Python Program to check if a # given string is a scrambled # form of another string  def isScramble(s1, s2):     n = len(s1)          # dp[i1][i2][l] indicates whether      # s1[i1:i1+l] can scramble into s2[i2:i2+l]     dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)]          # Base case: substrings of length 1     for i1 in range(n):         for i2 in range(n):             dp[i1][i2][1] = (s1[i1] == s2[i2])          # Fill DP table for lengths from 2 to n     for l in range(2, n + 1):         for i1 in range(n - l + 1):             for i2 in range(n - l + 1):                 for length in range(1, l):                                          # Case 1: No swap                     noSwap = dp[i1][i2][length] and dp[i1 + length][i2 + length][l - length]                                          # Case 2: Swap                     swap = dp[i1][i2 + (l - length)][length] and dp[i1 + length][i2][l - length]                                          if noSwap or swap:                         dp[i1][i2][l] = True                         break          return dp[0][0][n]  if __name__ == "__main__":     s1 = "coder"     s2 = "ocred"          if isScramble(s1, s2):         print("Yes")     else:         print("No") 
C#
// C# Program to check if a // given string is a scrambled // form of another string  using System;  class GfG {          static bool isScramble(string s1, string s2) {         int n = s1.Length;                  // dp[i1][i2][l] indicates whether          // s1.Substring(i1, l) can scramble into s2.Substring(i2, l)         bool[,,] dp = new bool[n, n, n + 1];                  // Base case: substrings of length 1         for (int i1 = 0; i1 < n; ++i1) {             for (int i2 = 0; i2 < n; ++i2) {                 dp[i1, i2, 1] = (s1[i1] == s2[i2]);             }         }                  // Fill DP table for lengths from 2 to n         for (int l = 2; l <= n; ++l) {             for (int i1 = 0; i1 <= n - l; ++i1) {                 for (int i2 = 0; i2 <= n - l; ++i2) {                     for (int len = 1; len < l; ++len) {                                                  // Case 1: No swap                         bool noSwap = dp[i1, i2, len] &&                          dp[i1 + len, i2 + len, l - len];                                                  // Case 2: Swap                         bool swap = dp[i1, i2 + (l - len), len] &&                          dp[i1 + len, i2, l - len];                         if (noSwap || swap) {                             dp[i1, i2, l] = true;                             break;                         }                     }                 }             }         }                  return dp[0, 0, n];     }      static void Main() {         string s1 = "coder";         string s2 = "ocred";                  if (isScramble(s1, s2)) {             Console.WriteLine("Yes");         } else {             Console.WriteLine("No");         }     } } 
JavaScript
// JavaScript Program to check if a // given string is a scrambled // form of another string  function isScramble(s1, s2) {     let n = s1.length;          // dp[i1][i2][l] indicates whether      // s1.substring(i1, i1 + l) can scramble into s2.substring(i2, i2 + l)     let dp = Array.from({ length: n }, () =>          Array.from({ length: n }, () =>              Array(n + 1).fill(false)         )     );          // Base case: substrings of length 1     for (let i1 = 0; i1 < n; ++i1) {         for (let i2 = 0; i2 < n; ++i2) {             dp[i1][i2][1] = (s1[i1] === s2[i2]);         }     }          // Fill DP table for lengths from 2 to n     for (let l = 2; l <= n; ++l) {         for (let i1 = 0; i1 <= n - l; ++i1) {             for (let i2 = 0; i2 <= n - l; ++i2) {                 for (let len = 1; len < l; ++len) {                                          // Case 1: No swap                     let noSwap = dp[i1][i2][len] &&                      dp[i1 + len][i2 + len][l - len];                                          // Case 2: Swap                     let swap = dp[i1][i2 + (l - len)][len] &&                      dp[i1 + len][i2][l - len];                                          if (noSwap || swap) {                         dp[i1][i2][l] = true;                         break;                     }                 }             }         }     }          return dp[0][0][n]; }  let s1 = "coder"; let s2 = "ocred";  if (isScramble(s1, s2)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes

Next Article
Check if a string is a scrambled form of another string

A

amarjeet_singh
Improve
Article Tags :
  • Strings
  • Tree
  • Algorithms
  • Divide and Conquer
  • Recursion
  • DSA
Practice Tags :
  • Algorithms
  • Divide and Conquer
  • Recursion
  • Strings
  • Tree

Similar Reads

    Check if a string is concatenation of another given string
    Given two strings str1 and str2 of length N and M respectively, the task is to check if the string str1 can be formed by concatenating the string str2 repetitively or not. Examples: Input: str1 = “abcabcabc”, str2 = “abc”Output: YesExplanation: Concatenating the string str2 thrice generates the stri
    7 min read
    Check if the given string is shuffled substring of another string
    Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print "YES" if str1 is a substring in shuffled form of str2 else print "NO". Example Input: str1 = "onetwofour", str2 = "hellofourtwooneworld" Output: YES Explanation: str1 is substring in sh
    15 min read
    Check if string S1 can be formed using repeated insertions of another string S2
    Given two strings S1 and S2 consisting of unique characters, the task is to check S1 can be formed by repeated insertions of string S2. Input: S1 = "aabb", S2 = "ab"Output: YesExplanation: the mentioned string can be obtained after series of moves: Insert string "ab" in an empty string. Current stri
    7 min read
    Check if String formed by first and last X characters of a String is a Palindrome
    Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
    5 min read
    Check if a given string is a rotation of a palindrome
    Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences