Interleaving String
Interleaving String is a medium dynamic programming problem solved with the strings pattern.
The best approach, optimal (1d dp, one row), runs in O(m · n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from recursion with memo up.
Problem
You are given three strings s1, s2 and s3. Decide whether s3 can be built by interleaving s1 and s2: splitting each of s1 and s2 into pieces and merging those pieces into one string so that every character of s1 and of s2 is used exactly once, and the characters of each source keep their original relative order.
In other words, reading s3 from left to right, you take each next character from the front of what is left of s1 or from the front of what is left of s2, and you must use up both strings exactly. Return true if this is possible and false otherwise.
Examples
Example 1
- Input
s1 = "dog", s2 = "cat", s3 = "dcoagt"- Output
true- Why
- Take d (s1), c (s2), o (s1), a (s2), g (s1), t (s2). Each source string is read in its own order.
Example 2
- Input
s1 = "ab", s2 = "ba", s3 = "aabb"- Output
false- Why
- The first a must come from s1. The next character is a, but s1 offers b and s2 offers b, so nothing can supply it.
Example 3
- Input
s1 = "", s2 = "q", s3 = "q"- Output
true- Why
- With s1 empty, s3 just has to equal s2.
Constraints
0 <= s1.length, s2.length <= 1000 <= s3.length <= 200- All three strings contain only lowercase English letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursion with memo | O(m · n) | O(m · n) |
| 2D DP table | O(m · n) | O(m · n) |
| Optimal (1D DP, one row) | O(m · n) | O(n) |
1Recursion with memo
O(m · n)There are (m + 1)(n + 1) states for m = s1.length and n = s2.length, each solved once in constant time.O(m · n)The memo table, plus a recursion stack up to m + n deep.Use characters from the fronts of s1 and s2 to rebuild s3. At state (i, j) the next needed character is s3[i + j]: take it from s1 if s1[i] matches, or from s2 if s2[j] matches, and try both when both match. Caching (i, j) avoids exploring the same state twice.
- If the lengths do not add up, return false.
- can(i, j): if i == s1.length and j == s2.length, return true.
- Let k = i + j. If s1[i] == s3[k] and can(i + 1, j), the answer is true.
- Otherwise, if s2[j] == s3[k] and can(i, j + 1), the answer is true; else false.
- Store each answer in memo[i][j].
class Solution {
private Boolean[][] memo;
private String s1, s2, s3;
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) return false;
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
memo = new Boolean[s1.length() + 1][s2.length() + 1];
return can(0, 0);
}
private boolean can(int i, int j) {
if (i == s1.length() && j == s2.length()) return true;
if (memo[i][j] != null) return memo[i][j];
int k = i + j;
boolean ok = false;
if (i < s1.length() && s1.charAt(i) == s3.charAt(k)) ok = can(i + 1, j);
if (!ok && j < s2.length() && s2.charAt(j) == s3.charAt(k)) ok = can(i, j + 1);
memo[i][j] = ok;
return ok;
}
}class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
memo = {}
def can(i: int, j: int) -> bool:
if i == m and j == n:
return True
if (i, j) in memo:
return memo[(i, j)]
k = i + j
ok = False
if i < m and s1[i] == s3[k]:
ok = can(i + 1, j)
if not ok and j < n and s2[j] == s3[k]:
ok = can(i, j + 1)
memo[(i, j)] = ok
return ok
return can(0, 0)class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size()) return false;
a = s1;
b = s2;
c = s3;
memo.assign(s1.size() + 1, vector<int>(s2.size() + 1, -1));
return can(0, 0);
}
private:
string a, b, c;
vector<vector<int>> memo;
bool can(int i, int j) {
int m = (int)a.size(), n = (int)b.size();
if (i == m && j == n) return true;
if (memo[i][j] != -1) return memo[i][j];
int k = i + j;
bool ok = false;
if (i < m && a[i] == c[k]) ok = can(i + 1, j);
if (!ok && j < n && b[j] == c[k]) ok = can(i, j + 1);
memo[i][j] = ok;
return ok;
}
};function isInterleave(s1, s2, s3) {
const m = s1.length, n = s2.length;
if (m + n !== s3.length) return false;
const memo = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(null));
function can(i, j) {
if (i === m && j === n) return true;
if (memo[i][j] !== null) return memo[i][j];
const k = i + j;
let ok = false;
if (i < m && s1[i] === s3[k]) ok = can(i + 1, j);
if (!ok && j < n && s2[j] === s3[k]) ok = can(i, j + 1);
memo[i][j] = ok;
return ok;
}
return can(0, 0);
}22D DP table
O(m · n)(m + 1)(n + 1) cells, each from two neighbours in constant time.O(m · n)The full (m + 1) × (n + 1) table.Fill the same states bottom-up. dp[i][j] says whether the first i letters of s1 and the first j letters of s2 can be woven into the first i + j letters of s3. The last letter used came either from s1 (from dp[i - 1][j]) or from s2 (from dp[i][j - 1]).
- If the lengths do not add up, return false.
- dp[0][0] = true: nothing from either string forms the empty prefix.
- For every (i, j): dp[i][j] is true if i > 0, dp[i - 1][j] and s1[i - 1] == s3[i + j - 1], or if j > 0, dp[i][j - 1] and s2[j - 1] == s3[i + j - 1].
- Return dp[m][n].
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 && dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) dp[i][j] = true;
if (j > 0 && dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1)) dp[i][j] = true;
}
}
return dp[m][n];
}
}class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
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 dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]:
dp[i][j] = True
if j > 0 and dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]:
dp[i][j] = True
return dp[m][n]class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int m = (int)s1.size(), n = (int)s2.size();
if (m + n != (int)s3.size()) return false;
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i > 0 && dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]) dp[i][j] = true;
if (j > 0 && dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]) dp[i][j] = true;
}
}
return dp[m][n];
}
};function isInterleave(s1, s2, s3) {
const m = s1.length, n = s2.length;
if (m + n !== s3.length) return false;
const dp = Array.from({ length: m + 1 }, () => 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 && dp[i - 1][j] && s1[i - 1] === s3[i + j - 1]) dp[i][j] = true;
if (j > 0 && dp[i][j - 1] && s2[j - 1] === s3[i + j - 1]) dp[i][j] = true;
}
}
return dp[m][n];
}3Optimal (1D DP, one row)
O(m · n)Still one constant-time update per (i, j) pair.O(n)A single row of n + 1 booleans.Row i of the table only reads row i - 1 (the cell straight above) and the cell to its left in the same row. Keep a single array: before it is overwritten, dp[j] still holds the value from the row above, and dp[j - 1] already holds the new value to the left.
- If the lengths do not add up, return false.
- Use dp of size n + 1. For i from 0 to m and j from 0 to n:
- At (0, 0) set dp[0] = true. Otherwise dp[j] = (i > 0 and dp[j] and s1[i - 1] == s3[i + j - 1]) or (j > 0 and dp[j - 1] and s2[j - 1] == s3[i + j - 1]).
- Return dp[n].
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[n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 && j == 0) {
dp[j] = true;
} else {
boolean fromS1 = i > 0 && dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);
boolean fromS2 = j > 0 && dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);
dp[j] = fromS1 || fromS2;
}
}
}
return dp[n];
}
}class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
m, n = len(s1), len(s2)
if m + n != len(s3):
return False
dp = [False] * (n + 1)
for i in range(m + 1):
for j in range(n + 1):
if i == 0 and j == 0:
dp[j] = True
else:
from_s1 = i > 0 and dp[j] and s1[i - 1] == s3[i + j - 1]
from_s2 = j > 0 and dp[j - 1] and s2[j - 1] == s3[i + j - 1]
dp[j] = from_s1 or from_s2
return dp[n]class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int m = (int)s1.size(), n = (int)s2.size();
if (m + n != (int)s3.size()) return false;
vector<bool> dp(n + 1, false);
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 && j == 0) {
dp[j] = true;
} else {
bool fromS1 = i > 0 && dp[j] && s1[i - 1] == s3[i + j - 1];
bool fromS2 = j > 0 && dp[j - 1] && s2[j - 1] == s3[i + j - 1];
dp[j] = fromS1 || fromS2;
}
}
}
return dp[n];
}
};function isInterleave(s1, s2, s3) {
const m = s1.length, n = s2.length;
if (m + n !== s3.length) return false;
const dp = new Array(n + 1).fill(false);
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i === 0 && j === 0) {
dp[j] = true;
} else {
const fromS1 = i > 0 && dp[j] && s1[i - 1] === s3[i + j - 1];
const fromS2 = j > 0 && dp[j - 1] && s2[j - 1] === s3[i + j - 1];
dp[j] = fromS1 || fromS2;
}
}
}
return dp[n];
}Edge cases to test
- All three strings empty (true)
- One source empty: s3 must equal the other
- Lengths that do not add up (false right away)
- Both sources offer the same next letter, so a greedy pick can go wrong
- Same letters, wrong order (false)
Hints
Hint 1
If s1.length + s2.length is not s3.length, the answer is false.
Hint 2
Once i characters of s1 and j of s2 are used, the next character of s3 is at index i + j. So the state is just (i, j).
Hint 3
dp[i][j] is true when the first i letters of s1 and the first j of s2 can form the first i + j of s3. It comes from dp[i - 1][j] or dp[i][j - 1], and one row at a time is enough.
FAQ
What is the best time complexity for Interleaving String?
Optimal (1D DP, one row) runs in O(m · n) time and O(n) extra space. Still one constant-time update per (i, j) pair.
Which pattern does Interleaving String use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Common Subsequence, Longest Palindromic Subsequence.
Is there a brute force solution for Interleaving String?
Yes. Recursion with memo takes O(m · n) time and O(m · n) space. Use characters from the fronts of s1 and s2 to rebuild s3.
Which edge cases should I test for Interleaving String?
All three strings empty (true); One source empty: s3 must equal the other; Lengths that do not add up (false right away); Both sources offer the same next letter, so a greedy pick can go wrong; Same letters, wrong order (false).