Interleaving String

Decide whether a third string merges two strings while each of them keeps its own order.

Given three strings s1, s2 and s3, return true if s3 can be built by merging every character of s1 and s2 into one string, where the characters of each string stay in their original order. Such a merge is called an interleaving of s1 and s2.

Example 1
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
Example 3
Input: s1 = "", s2 = "", s3 = ""
Output: true
Solution

The Idea

Picture two short decks of cards being shuffled together. Cards drop from the left deck and the right deck in any mix, yet the cards of each deck come out in the order they had in that deck. An interleaving is the same shuffle, with letters instead of cards.

Take a small case: s1 = "ab", s2 = "ac" and s3 = "acab". Read s3 from the left. Its first letter is a, and both s1 and s2 start with a. Say we take it from s1. The next letter of s3 is c, but s1 now offers b and s2 offers a, so we are stuck.

Taking that first a from s2 instead works: s2 then offers c, which matches, and the letters left in s3, "ab", are exactly s1. So the answer is true. Always taking from s1 when it matches, because it looks right at that moment, is called a greedy choice. It answers false here, and it answers false for Example 1 too.

So when both strings offer the needed letter, both choices have to be followed. Do we then have to remember every order of choices made so far? No. After any run of choices, all that matters is how many letters came from s1 and how many from s2. Together those letters match the start of s3, and the rest of the work depends only on those two counts.

That gives a small table, with one row for each count of letters taken from s1 and one column for each count taken from s2. Each cell says whether those letters can be merged into the start of s3 of the same length. The picture below fills in this table for "acab".

The table for s1 = ab, s2 = ac, s3 = acab. Rows count the characters taken from s1, columns the characters taken from s2. The highlighted path takes a and c from s2, then a and b from s1, and ends at true in the bottom right cell. Taking the first a from s1 leads only to false cells.

The top left cell takes nothing from either string, so "s3 so far" is empty and the cell is true. An arrow right takes the next character of s2. In the row labelled none, the cells under "a" and "ac" are true, because s3 starts with "a" and then "ac". From there the highlighted path goes down twice, taking a and then b from s1, and reaches "acab" in the bottom right cell, the answer.

The dashed arrow is the greedy start. Taking a from s1 gives a true cell in row "a", column none, but both cells after it are false. In row "a", column "a", the letters are a and a, while s3 starts with "ac". In row "ab", column none, s1 alone gives "ab", not "ac".

Every cell is filled from the cell above it or the cell to its left, which were filled earlier. Answering the full question by filling in a table of these smaller answers, each built from ones already found, is called dynamic programming.

Solution Approach

Turning the table into code means settling three things: what one cell means, how a cell is filled from its neighbours, and in which order the cells are filled. Two more questions are worth a look: why trying every choice is slow, and how to keep less of the table.

What one cell means

How do we name a cell in code? Call the table dp. Then dp[i][j] is true when the first i characters of s1 and the first j characters of s2 can be merged into the first i + j characters of s3.

With m the length of s1 and n the length of s2, the table has m + 1 rows and n + 1 columns, since taking no characters is a count too. The answer is dp[m][n], which uses every character. If m + n differs from the length of s3, no merge can match it, so the method returns false before building anything.

Filling a cell from its neighbours

Which character did the merge add last? It is the newest character of s3 in the cell, at index i + j - 1, counting from 0. It came either from s1 or from s2, and the cell is true if either way works:

  • From s1: the cell above, dp[i - 1][j], is true, and character i - 1 of s1 equals the newest character.
  • From s2: the cell to the left, dp[i][j - 1], is true, and character j - 1 of s2 equals the newest character.

In the picture, the cell in row "ab", column "ac" has "acab", whose newest character is b. The last character of s1 is b and the cell above it is true, so this cell is true. In row "a", column "a", the newest character is c, but s1 and s2 both offer a, so that cell is false.

The order of filling

Which cell goes first? The first is dp[0][0], which is true because two empty strings merge into an empty one. Then the cells are filled row by row, each row from left to right, so the cell above and the cell to the left are always ready. The top row has no cell above it, and the first column has none to its left, so each check also makes sure that neighbour exists.

Why trying every choice is slow

Why not simply follow both choices with a method that calls itself whenever both strings offer the needed letter? Each such tie splits the search in two, and the same counts are reached again and again through different orders. Take s1 and s2 as ten a's each and s3 as nineteen a's followed by b. That search makes 520,675 calls before it answers false, while the table for the same strings has 11 × 11 = 121 cells.

Keeping one row (optional)

Does the whole table have to stay in memory? A cell reads only the cell above and the cell to its left, so one array of n + 1 values is enough. Before position j is overwritten it still holds the row above, and position j - 1 already holds the current row. The full table is kept in the code below because it matches the picture.

Java Solution

The method isInterleave works in these steps:

  1. First, store the lengths of s1 and s2 in m and n, and return false when m + n differs from the length of s3.
  2. Create the table dp, a boolean array with m + 1 rows and n + 1 columns, and set dp[0][0] to true. Java starts every other cell as false.
  3. Fill the table with two loops, one inside the other. The outer loop moves i over the rows, from 0 to m, and the inner loop moves j over the columns, from 0 to n. The cell dp[0][0] is already set, so it is skipped.
  4. For every other cell, read the newest character of s3, at index i + j - 1, into c. Set the cell to true if the cell above is true and character i - 1 of s1 is c. Then do the same check with the cell to the left and character j - 1 of s2.
  5. When both loops are done, return dp[m][n].

The main method runs the three examples, the "acab" case from the picture, a case where c comes too early, an empty s2, and an s3 that is one character too long.

Java
public class InterleavingString {

    public static boolean isInterleave(String s1, String s2, String s3) {
        int m = s1.length();
        int n = s2.length();
        if (m + n != s3.length()) {
            return false;                              // lengths do not add up
        }
        // dp[i][j]: the first i characters of s1 and the first j of s2
        // can be merged into the first i + j characters of s3
        boolean[][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;                               // nothing taken, nothing to match
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i + j == 0) {
                    continue;
                }
                char c = s3.charAt(i + j - 1);         // the newest character of s3
                if (i > 0 && dp[i - 1][j] && s1.charAt(i - 1) == c) {
                    dp[i][j] = true;                   // it came from s1
                }
                if (j > 0 && dp[i][j - 1] && s2.charAt(j - 1) == c) {
                    dp[i][j] = true;                   // it came from s2
                }
            }
        }
        return dp[m][n];
    }

    public static void main(String[] args) {
        System.out.println(isInterleave("aabcc", "dbbca", "aadbbcbcac"));
        System.out.println(isInterleave("aabcc", "dbbca", "aadbbbaccc"));
        System.out.println(isInterleave("", "", ""));
        System.out.println(isInterleave("ab", "ac", "acab"));    // first 'a' must come from s2
        System.out.println(isInterleave("ab", "ac", "abca"));    // c comes before s2's a
        System.out.println(isInterleave("abc", "", "abc"));      // s2 is empty
        System.out.println(isInterleave("ab", "c", "abcd"));     // one character too many
    }
}

Running it prints:

Output
true
false
true
true
false
true
false

Look at the second line. Example 2 uses the same letters as Example 1, three a's, three b's, three c's and one d, yet it prints false. Counting letters is not enough. In s2 the a comes after a c, but in "aadbbbaccc" every c comes after the last a.

The fourth line is the "acab" case from the picture, and it prints true even though a greedy start fails on it. On the fifth line, "abca" puts c before the a of s2, which breaks the order of "ac", so it prints false. With an empty s2, the table has a single column, and the sixth line is true because s3 equals s1. The last line is false from the length check alone, since "abcd" has four characters and the other two have three together.

Complexity

The work is deciding each true or false cell once, from at most two neighbours.

  • Time: O(m × n), because the two loops visit each of the (m + 1) × (n + 1) cells once, and each cell compares at most two characters.
  • Space: O(m × n), because the table keeps one true or false value for every pair of counts taken from s1 and s2; the one-row version brings this down to O(n).

A table indexed by "first i characters of one string, first j of the other" also solves Longest Common Subsequence.