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 s1 and s2 of the same length, made of lowercase English letters, return true if s2 can come out of scrambling s1, and false otherwise.

Example 1
Input: s1 = "great", s2 = "rgeat"
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
Input: s1 = "abcde", s2 = "caebd"
Output: false
Example 3
Input: s1 = "a", s2 = "a"
Output: true
Solution

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 that block sits at the front if the pieces were kept in order, or at the back if they were swapped.

Look at the picture below. Both panels cut s1 = "great" after 2 letters, and the small numbers above the letters are their positions.

Two panels for s1 = great cut after 2 letters into gr and eat. In the panel halves kept in order, gr pairs with rg, the first two letters of s2, and eat with eat; both answers are yes. In the panel halves swapped, gr pairs with at, the last two letters of s2, and the letters differ, so the answer is no.

In the panel labelled "halves kept in order", "gr" is paired with the first two letters of s2, "rg", and "eat" with "eat". In the panel labelled "halves swapped", "gr" is paired with the last two letters of s2, "at". Those letters differ, so the pairing drawn in orange fails, and "eat" against "rge" never needs checking.

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. The faster way asks smaller questions instead, which means settling four things: what each cut point asks, which pieces need no cutting, how to name a piece, and how to avoid answering the same question twice.

Listing every scramble

Why not build every scramble of s1 and look for s2 among them? The list grows fast. "great" has 90 different scrambles, and the seven letters "abcdefg" already have 1,806, each of which would be built and compared.

Smaller questions for each cut point

What exactly does one cut point ask? Say we are comparing a piece of s1 with a piece of s2, both len letters long, and the cut comes after k letters, where k goes from 1 to len - 1. With the halves kept in order, the first k letters of the s2 piece must be a scramble of the first k letters of the s1 piece, and the rest must be a scramble of the rest.

With the halves swapped, the last k letters of the s2 piece pair with the first k letters of the s1 piece. The first len - k letters of the s2 piece then pair with the remaining len - k letters of the s1 piece. For "great" and k = 2, these are the two panels of the picture.

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 s1 piece adds one to its counter, each letter of the s2 piece takes one away, and any counter left above or below zero means the letters differ.

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 String with substring copies its letters every time. Every piece is a run of neighbouring letters inside s1 or s2, so three numbers describe a pair of pieces. The number i is where the s1 piece starts, j is where the s2 piece starts, and len is their shared length.

In the picture, "gr" against "at" is i = 0, j = 3 and len = 2.

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 s1 = "aaaaaaaaaaab" and s2 = "aaaaaabaaaaa", the search asks 2,835 questions when it forgets its answers, and 136 when it keeps them.

So each answer goes into a table, memo, the moment it is known. The entry memo[i][j][len] holds the answer for the s1 piece starting at i and the s2 piece starting at j, both len letters long. It stays null until that pair has been worked out, and every question looks there first, before any other work.

After Example 1, for instance, memo[0][0][2] is true ("gr" against "rg") and memo[0][3][2] is false ("gr" against "at"). Answering "great" against "rgeat" from the answers for shorter pieces is called dynamic programming. Keeping each piece's answer, so that a repeat costs one lookup, is called memoization.

Java Solution

The method isScramble and its helper check work in these steps:

  1. First, isScramble returns false if s1 and s2 have different lengths. Otherwise it stores both strings in fields and creates the table memo as a Boolean[n][n][n + 1], where n is the length of s1, so every entry starts as null.
  2. The helper method check(i, j, len) answers the question for the s1 piece starting at i and the s2 piece starting at j, both len letters long. So isScramble returns check(0, 0, n), the answer for the whole strings.
  3. Inside check, an entry memo[i][j][len] that is not null is returned at once.
  4. Next, s1.regionMatches(i, s2, j, len) compares the two pieces letter by letter without copying them. Equal pieces store true and return.
  5. Then the array count, with one counter per letter, adds each letter of the s1 piece and subtracts each letter of the s2 piece. A counter that is not zero stores false and returns.
  6. Otherwise a loop moves k, the length of the first part, from 1 to len - 1. For each k, kept checks the halves in order and swapped checks them swapped, each with two calls to check on shorter pieces. The two calls are joined by &&, so the second runs only if the first says yes.
  7. Each k sets result to kept || swapped, and the loop stops as soon as result is true. Finally check stores result in memo[i][j][len] and returns it.

The main method runs the three examples, then "abc" against "bca", "abcd" against "bdac", a word against its reverse, two words with different letters, and "aaaaaaaaaaab" against "aaaaaabaaaaa".

Java
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:

Output
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 answers every repeat.

  • 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 memo has n × n × (n + 1) entries, while at most n calls to check wait on each other, each on a shorter piece than its caller.

More examples of keeping the answers of a method that calls itself are in Dynamic Programming Basics.