Interleaving String
Decide whether a third string merges two strings while each of them keeps its own order.
Given three strings s1s2s3s3s1s2s1s2
Example 1
Output: true
Example 2
Output: false
Example 3
Output: true
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"s3 = "acab"s3s1s2s1s3s1s2
Taking that first a from s2s2s3s1s1
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 s1s2s3
That gives a small table, with one row for each count of letters taken from s1s2s3
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 s2s3s1
The dashed arrow is the greedy start. Taking a from s1s3s1
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 dpdp[i][j]is1js2i + js3
With ms1ns2m + 1n + 1dp[m][n]m + ns3
Filling a cell from its neighbours
Which character did the merge add last? It is the newest character of s3i + j - 1s1s2
- From
: the cell above,s1 , is true, and characterdp[i - 1][j] ofi - 1 equals the newest character.s1 - From
: the cell to the left,s2 , is true, and characterdp[i][j - 1] ofj - 1 equals the newest character.s2
In the picture, the cell in row "ab", column "ac" has "acab", whose newest character is b. The last character of s1s1s2
The order of filling
Which cell goes first? The first is dp[0][0]
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 s1s2s3
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 + 1jj - 1
Java Solution
The method isInterleave
- First, store the lengths of
ands1 ins2 andm , and return false whenn differs from the length ofm + n .s3 - Create the table
, adp array withboolean rows andm + 1 columns, and setn + 1 to true. Java starts every other cell as false.dp[0][0] - Fill the table with two loops, one inside the other. The outer loop moves
over the rows, from 0 toi , and the inner loop movesm over the columns, from 0 toj . The celln is already set, so it is skipped.dp[0][0] - For every other cell, read the newest character of
, at indexs3 , intoi + j - 1 . Set the cell to true if the cell above is true and characterc ofi - 1 iss1 . Then do the same check with the cell to the left and characterc ofj - 1 .s2 - When both loops are done, return
.dp[m][n]
The mains2s3
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:
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 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 s2s2s3s1
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
ands1 ; the one-row version brings this down to O(n).s2
A table indexed by "first i characters of one string, first j of the other" also solves