Interleaving String
Medium
Topics
Given strings s1, s2, and s3, return true if s3 is formed by an interleaving of s1 and s2 (preserving the order of each).
Example 1
s1
s2
s3
from s1from s2
Every character of
s3 is traced back to the string it came from, and within each source the characters keep their original order — only the two sources are shuffled together. Since that is possible here, the answer is true.The two sources and the string they are meant to interleave into.
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true
Example 2
s1
s2
s3
No way of shuffling
s1 and s2 together, keeping each one’s characters in order, produces s3 — so the answer is false. Note that the lengths alone must add up before anything else can.Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" Output: false
Constraints
- 0 <= s1.length, s2.length <= 100
- s3.length == s1.length + s2.length
- Inputs are lowercase letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Let dp[i][j] mean the first i chars of s1 and first j of s2 can interleave to form the first i+j chars of s3. Each step consumes one char from s1 or s2 if it matches the next char of s3.
Approach
- If lengths do not add up, return false.
- dp[0][0] = true. dp[i][j] is true if (s1[i-1]==s3[i+j-1] and dp[i-1][j]) or (s2[j-1]==s3[i+j-1] and dp[i][j-1]).
- Answer is dp[m][n].
Dry Run
s1 = "aabcc" s2 = "dbbca" s3 = "aadbbcbcac"
dp[i][j] = "the first i of s1 and the first j of s2 interleave to the first i+j of
s3". The index into s3 is implied by i + j, which is why no third dimension is
needed.
"" d b b c a
"" T . . . . .
a T . . . . .
a T T T T T .
b . T T . T .
c . . T T T T
c . . . T . T
answer dp[5][5] = true
Each true cell is reachable from above (take the next character of s1) or from the
left (take the next of s2), and only if that character matches s3 at position
i + j - 1. The Ts wander diagonally across the table, which is the picture of the
two strings alternating.
Greedy does not work, and this input shows exactly where it goes wrong. A
"prefer s1 whenever it matches" walk agrees for the first three characters and
then diverges at s3[3] = 'b', taking it from s1 because s1[2] is also 'b'. It
keeps going and gets stuck at s3[8] = 'a' with s1 exhausted and s2 offering a 'c'.
The valid split takes that 'b' from s2 instead:
"aa" from s1, then "dbbc" from s2, then "bc" from s1, then "a" from s2, then "c"
Which string supplies a character cannot be decided locally, because both can
match and only one choice survives nine characters later. That is the whole reason
for the table.
Note row b column b is false while its neighbours are true. Being reachable is not
inherited; each cell needs its own matching character, which is what stops the
table filling in uniformly.Complexity
- Time — O(m*n): fill the table once.
- Space — O(m*n): the DP grid (reducible to O(n)).
Common Pitfalls
- A greedy char-by-char match fails; you need the full DP because either string could supply the next char.
Full Solution — all languages
class Solution:
def isInterleave(self, s1, s2, s3):
m,n=len(s1),len(s2)
if m+n!=len(s3): return False
dp=[[False]*(n+1) for _ in range(m+1)]
dp[0][0]=True
for i in range(m+1):
for j in range(n+1):
if i>0 and s1[i-1]==s3[i+j-1] and dp[i-1][j]: dp[i][j]=True
if j>0 and s2[j-1]==s3[i+j-1] and dp[i][j-1]: dp[i][j]=True
return dp[m][n]import java.util.*;
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m=s1.length(),n=s2.length();
if(m+n!=s3.length())return false;
boolean[][] dp=new boolean[m+1][n+1];
dp[0][0]=true;
for(int i=0;i<=m;i++)for(int j=0;j<=n;j++) {
if(i>0&&s1.charAt(i-1)==s3.charAt(i+j-1)&&dp[i-1][j])dp[i][j]=true;
if(j>0&&s2.charAt(j-1)==s3.charAt(i+j-1)&&dp[i][j-1])dp[i][j]=true;
}
return dp[m][n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isInterleave(string s1, string s2, string s3) {
int m=s1.size(),n=s2.size();
if(m+n!=(int)s3.size())return false;
vector<vector<char>> dp(m+1,vector<char>(n+1,0));
dp[0][0]=1;
for(int i=0;i<=m;i++)for(int j=0;j<=n;j++) {
if(i>0&&s1[i-1]==s3[i+j-1]&&dp[i-1][j])dp[i][j]=1;
if(j>0&&s2[j-1]==s3[i+j-1]&&dp[i][j-1])dp[i][j]=1;
}
return dp[m][n];
}
};/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/ var isInterleave = function(s1, s2, s3) {
const m=s1.length,n=s2.length;
if(m+n!==s3.length)return false;
const dp=[];
for(let i=0;i<=m;i++)dp.push(new Array(n+1).fill(false));
dp[0][0]=true;
for(let i=0;i<=m;i++)for(let j=0;j<=n;j++) {
if(i>0&&s1[i-1]===s3[i+j-1]&&dp[i-1][j])dp[i][j]=true;
if(j>0&&s2[j-1]===s3[i+j-1]&&dp[i][j-1])dp[i][j]=true;
}
return dp[m][n];
};
Asked at
eBay