Last Updated : 12 Jul, 2025
Try it on GfG Practice
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:
[Naive Approach] Divide and Conquer Approach - Exponential TimeInput: 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"
C++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:
- 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].
- 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++ 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");
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.
The idea is to use dynamic programming to memoize subproblems where substrings of
s1
ands2
can be split and compared recursively under the scramble conditions. By capturing overlapping subproblems, we avoid redundant computations and improve efficiency.State Representation:
Definedp[i1][j1][i2][j2]
astrue
if the substrings1[i1...j1]
can be scrambled intos2[i2...j2]
.Recurrence Relation:
For every possible split pointlen
(1 ≤len
<j1 - i1 + 1
), check two scrambling conditions:
- No Swap:
Check if the firstlen
characters ofs1[i1...j1]
ands2[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]
- Swap:
Check if the firstlen
characters ofs1[i1...j1]
match the lastlen
characters ofs2[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:
Ifi1 == j1
(substring length 1), returns1[i1] == s2[i2]
.
C++Key Insight: The end indices
j1
andj2
can be derived from the start indicesi1
,i2
, and the substring lengthl
(sincej1 = i1 + l - 1
andj2 = i2 + l - 1
). This eliminates redundant parameters. Now the states can be defined as:
- Define
dp[i1][i2][l]
astrue
if the substring starting ati1
ins1
with lengthl
can be scrambled into the substring starting ati2
ins2
with the same lengthl
.Recurrence Relation:
For every possible splitlen
(1 ≤len
<l
), check:
- No Swap: dp[i1][i2][l] |= dp[i1][i2][len] && dp[i1+len][i2+len][l-len]
- Swap: dp[i1][i2][l] |= dp[i1][i2 + (l-len)][len] && dp[i1+len][i2][l-len]
Base Case:
Ifl == 1
, returns1[i1] == s2[i2]
.
// 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");
}
Time Complexity: O(n^4), where n is the length of the given strings.
Auxiliary Space: O(n^3), due to memoization.
C++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++ 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");
}
In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Here’s the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation Practice ProblemRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4