Scramble String
Decide whether one string can be made from another by cutting it into pieces and swapping them.
A string can be scrambled with this process. If the string has one character, stop. Otherwise split it into two non-empty parts at any point, either keep the two parts in order or swap them, and then scramble each part with the same process.
Given two strings s1s2s2s1
Example 1
Output: true
Explanation: split "great" into "gr" and "eat" and keep that order. Then split "gr" into "g" and "r" and swap them, which gives "rg". Every other split keeps its order.
Example 2
Output: false
Example 3
Output: true
The Idea
Write "great" on a strip of paper and cut it into two pieces, say "gr" and "eat". You may swap the two pieces or leave them in order. Then do the same with each piece on its own, again and again, until every piece is one letter. Whatever word the strip shows at the end is a scramble of "great".
Example 1 keeps "gr" and "eat" in order, cuts "gr" into "g" and "r", and swaps those two. The strip now reads "rgeat". But given only the two words, how can we tell whether some series of cuts and swaps leads from one to the other?
Start with the first cut. Once "great" is cut into "gr" and "eat", every later cut happens inside one of the two pieces. So the letters g and r stay together as a block of two. In s2
Look at the picture below. Both panels cut s1
In the panel labelled "halves kept in order", "gr" is paired with the first two letters of s2s2
The kept order works, but only because "gr" and "rg" are scrambles of each other. That is the same question again, on pieces of two letters: split "gr" after 1 letter, swap, and it reads "rg". We do not know where the first cut was made, so cuts after 1, 2, 3 and 4 letters all have to be tried.
So the question for two words turns into the same question for shorter pieces, one pair of questions for each cut point and each order. The pieces keep shrinking until they are single letters, and two single letters are simply compared.
Solution Approach
The slow way lists every scramble of s1
Listing every scramble
Why not build every scramble of s1s2
Smaller questions for each cut point
What exactly does one cut point ask? Say we are comparing a piece of s1s2lenkklen - 1ks2ks1
With the halves swapped, the last ks2ks1len - ks2len - ks1k
The answer is true as soon as one cut point works in one of the two orders, so the search stops there.
Answers without cutting
Which pieces can be answered right away? If the two pieces are equal, the answer is yes, because keeping every split in order changes nothing. If they hold different letters, the answer is no, because cutting and swapping only move letters around. That is how "gr" against "at" was ruled out in the picture.
To compare the letters, an array of 26 counters, one per letter, is enough. Each letter of the s1s2
The same letters are not enough for a yes, though. In Example 2, "abcde" and "caebd" use the same five letters, yet the answer is false. So when the letters match, the cut points still have to be tried. Two single letters are always settled right away, by one check or the other.
Describing a piece by positions
How should a piece be handed to the smaller question? Cutting it out as a new Stringsubstrings1s2is1js2len
In the picture, "gr" against "at" is ijlen
Remembering answers
Can the same pair of pieces come up twice? Yes, because different series of cuts can end at the same piece. Cutting "abcd" after 1 letter leaves "bcd", and cutting that after 1 letter leaves "cd". Cutting "abcd" after 2 letters reaches "cd" directly, so both paths can ask about "cd" against the same two letters of s2
The repeats add up. For s1s2
So each answer goes into a table, memomemo[i][j][len]s1is2jlennull
After Example 1, for instance, memo[0][0][2]memo[0][3][2]
Java Solution
The method isScramblecheck
- First,
returns false ifisScramble ands1 have different lengths. Otherwise it stores both strings in fields and creates the tables2 as amemo , whereBoolean[n][n][n + 1] is the length ofn , so every entry starts ass1 .null - The helper method
answers the question for thecheck(i, j, len) piece starting ats1 and thei piece starting ats2 , bothj letters long. Solen returnsisScramble , the answer for the whole strings.check(0, 0, n) - Inside
, an entrycheck that is notmemo[i][j][len] is returned at once.null - Next,
compares the two pieces letter by letter without copying them. Equal pieces store true and return.s1.regionMatches(i, s2, j, len) - Then the array
, with one counter per letter, adds each letter of thecount piece and subtracts each letter of thes1 piece. A counter that is not zero stores false and returns.s2 - Otherwise a loop moves
, the length of the first part, from 1 tok . For eachlen - 1 ,k checks the halves in order andkept checks them swapped, each with two calls toswapped on shorter pieces. The two calls are joined bycheck , so the second runs only if the first says yes.&& - Each
setsk toresult , and the loop stops as soon askept || swapped is true. Finallyresult storescheck inresult and returns it.memo[i][j][len]
The main
public class ScrambleString {
private String s1;
private String s2;
private Boolean[][][] memo; // memo[i][j][len]: null until worked out
public boolean isScramble(String s1, String s2) {
int n = s1.length();
if (n != s2.length()) {
return false;
}
this.s1 = s1;
this.s2 = s2;
this.memo = new Boolean[n][n][n + 1];
return check(0, 0, n);
}
// Is the piece of s2 starting at j a scramble of the piece of s1 starting at i,
// both len characters long?
private boolean check(int i, int j, int len) {
if (memo[i][j][len] != null) {
return memo[i][j][len]; // asked before: reuse the answer
}
if (s1.regionMatches(i, s2, j, len)) {
memo[i][j][len] = true; // equal pieces, nothing to rearrange
return true;
}
int[] count = new int[26];
for (int p = 0; p < len; p++) {
count[s1.charAt(i + p) - 'a']++;
count[s2.charAt(j + p) - 'a']--;
}
for (int c : count) {
if (c != 0) {
memo[i][j][len] = false; // different letters: no split can help
return false;
}
}
boolean result = false;
for (int k = 1; k < len && !result; k++) { // first part is k characters long
boolean kept = check(i, j, k) && check(i + k, j + k, len - k);
boolean swapped = check(i, j + len - k, k) && check(i + k, j, len - k);
result = kept || swapped;
}
memo[i][j][len] = result;
return result;
}
public static void main(String[] args) {
ScrambleString solver = new ScrambleString();
System.out.println(solver.isScramble("great", "rgeat"));
System.out.println(solver.isScramble("abcde", "caebd"));
System.out.println(solver.isScramble("a", "a"));
System.out.println(solver.isScramble("abc", "bca"));
System.out.println(solver.isScramble("abcd", "bdac"));
System.out.println(solver.isScramble("abcdefgh", "hgfedcba"));
System.out.println(solver.isScramble("abc", "abd"));
System.out.println(solver.isScramble("aaaaaaaaaaab", "aaaaaabaaaaa"));
}
}
Running it prints:
true
false
true
true
false
true
false
true
Look at the fifth line. "abcd" and "bdac" share all four letters, yet the answer is false. Whatever the first cut is, the block of letters before it has to sit at the front or the back of "bdac".
After 1 letter that block is "a", but "bdac" starts with b and ends with c. After 2 letters it is "ab", while the front "bd" and the back "ac" each hold another letter. After 3 letters the leftover "d" is at neither end either, so no first cut works.
The sixth line is true because "hgfedcba" is "abcdefgh" with every split swapped. The seventh, "abc" against "abd", is false from the letter count alone. The last line, true, is the pair that took 2,835 questions without the table and 136 with it.
Complexity
The work is one visit to each pair of pieces that gets asked about, since memo
- Time: O(n⁴), because each of the at most n × n × n pairs of pieces (two starts and a length) is worked out once, with a letter count and up to n cut points.
- Space: O(n³), because
has n × n × (n + 1) entries, while at most n calls tomemo wait on each other, each on a shorter piece than its caller.check
More examples of keeping the answers of a method that calls itself are in