15% off all plans & roadmaps Use code
See plansInterleaving String
- LeetCode 97
- Medium
- Dynamic Programming (DP) Patterns
- 2D Array (Unique Paths on Grid)
Updated
TL;DR: Decide whether s3 can be built by weaving s1 and s2 together while keeping each string's order. Track how many characters you took from each string as a grid cell (i, j) and fill the grid with DP in O(n * m) time.
Problem
You are given three strings s1, s2 and s3. Decide whether s3 can be built by interleaving s1 and s2.
An interleaving keeps the left-to-right order of the characters taken from s1, and separately keeps the order of the characters taken from s2. At each position, the next character of s3 comes from one of the two strings.
Every character of both s1 and s2 must be used exactly once, so s3 must have length s1.length + s2.length. Return true if at least one valid interleaving produces s3, otherwise return false.
Example 1
Input: s1 = "cat", s2 = "dog", s3 = "cdoatg" Output: true Explanation: Take c from s1, then d and o from s2, then a and t from s1, and finally g from s2.
Example 2
Input: s1 = "ab", s2 = "ba", s3 = "bbaa" Output: false Explanation: After taking b from s2, the next b cannot come from either string. s2 must continue with a, and s1 starts with a.
Example 3
Input: s1 = "", s2 = "hello", s3 = "hello" Output: true Explanation: When s1 is empty, the only interleaving uses all of s2, which matches s3 exactly.
Constraints
0 <= s1.length <= 1000 <= s2.length <= 1000 <= s3.length <= 200s1,s2ands3contain only lowercase English letterss3.length = s1.length + s2.length
Constraints that matter
- s1 and s2 are at most 100 characters each, so the number of (i, j) states is at most 101 * 101 = 10,201. A table over all states is tiny, and an O(n * m) solution runs instantly.
- Each step has up to two choices, so the unmemoized search can reach 2^200 paths. That is far beyond any time limit and forces you to cache states.
- s3.length equals s1.length + s2.length is stated, but you should still check it first. It makes the index i + j safe and ends many inputs in constant time.
- Only lowercase letters appear, so no special encoding is needed. Comparing characters directly is enough.
- s1 and s2 may be empty. Your table and loops must handle row 0 and column 0 without reading index -1.
Hints
Hint 1
This is a 2D dynamic programming problem on a grid.
Hint 2
Try every way to build s3.
Solution
Intuition
This is a 2D dynamic programming problem on a grid. After you have used i characters of s1 and j characters of s2, you have written exactly i + j characters of s3. So the pair (i, j) fully describes where you are. Nothing else about the history matters.
Picture one row of mailboxes you repaint as you walk down a street, with the array dp as that row. Each box keeps its old label until you overwrite it, so dp[j] is the cell above and dp[j-1] is the cell to the left.
Think of (i, j) as a cell. Taking the next character of s1 moves you down one row. Taking the next character of s2 moves you right one column. You start at (0, 0) and want to reach (n, m), where n and m are the lengths of s1 and s2. A move is allowed only when the character you take equals s3[i + j].
This matches the unique-paths-on-a-grid pattern, with some cells blocked by character mismatches. The question becomes whether a path of allowed moves leads from the top-left to the bottom-right corner.
Many different move orders land on the same cell. Taking s1 then s2 reaches the same (1, 1) as s2 then s1. Searching without remembering cells redoes that work an exponential number of times. Remember each cell once and the work drops to the number of cells.
Worked example
Input: s1 = "", s2 = "hello", s3 = "hello" Output: true Explanation: With s1 empty, every character of s3 must come from s2 in order. s2 is "hello" and s3 is "hello", so each of the five characters matches and all of s2 is consumed.
Approach 1: Brute force recursion
Try every way to build s3. At state (i, j), look at s3[i + j]. If it equals s1[i], take it and recurse on (i + 1, j). If it equals s2[j], take it and recurse on (i, j + 1).
When both strings are fully used, you have built all of s3, so return true. Check n + m == len(s3) first. With that check passing, using both strings completely means s3 is completely used too.
Steps
- Return false if
len(s1) + len(s2) != len(s3). - Define
go(i, j)whereiandjcount characters already taken froms1ands2. - If
i == nandj == m, return true. - If
i < nands1[i] == s3[i + j], andgo(i + 1, j)is true, return true. - If
j < mands2[j] == s3[i + j], andgo(i, j + 1)is true, return true. - Otherwise return false, and call
go(0, 0).
Dry run
Trace on s1 = "", s2 = "hello", s3 = "hello". Here n = 0 and m = 5.
go(0, 0):i == n, so thes1branch is skipped.s2[0] = hequalss3[0] = h, so callgo(0, 1).go(0, 1):s2[1] = eequalss3[1], so callgo(0, 2).go(0, 2),go(0, 3)andgo(0, 4)matchl,l,othe same way.go(0, 5):i == 0 == nandj == 5 == m, so return true.
True propagates back through all five calls and the answer is true. With one empty string there is no branching. Inputs where both strings match s3[k] split into two calls, and that is where the cost explodes.
Complexity
| Time | O(2^(n + m)) |
|---|---|
| Space | O(n + m) |
Let n and m be the lengths of s1 and s2. Each call moves one character forward, so the recursion depth is at most n + m, and that depth is the stack space. Each call makes at most two child calls, so the call tree has at most 2^(n + m) nodes. The same (i, j) is reached by many paths and recomputed each time, which is why this is too slow for n = m = 100.
PythonTested in our runner
from typing import List, Optional
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m = len(s1), len(s2)
if n + m != len(s3):
return False
def go(i: int, j: int) -> bool:
if i == n and j == m:
return True
k = i + j
if i < n and s1[i] == s3[k] and go(i + 1, j):
return True
if j < m and s2[j] == s3[k] and go(i, j + 1):
return True
return False
return go(0, 0)JavaTested in our runner
import java.util.*;
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) {
return false;
}
return go(0, 0, s1, s2, s3);
}
private boolean go(int i, int j, String s1, String s2, String s3) {
if (i == s1.length() && j == s2.length()) {
return true;
}
int k = i + j;
if (i < s1.length() && s1.charAt(i) == s3.charAt(k) && go(i + 1, j, s1, s2, s3)) {
return true;
}
if (j < s2.length() && s2.charAt(j) == s3.charAt(k) && go(i, j + 1, s1, s2, s3)) {
return true;
}
return false;
}
};C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
if (s1.size() + s2.size() != s3.size()) {
return false;
}
return go(0, 0, s1, s2, s3);
}
private:
bool go(int i, int j, const string& s1, const string& s2, const string& s3) {
int n = s1.size(), m = s2.size();
if (i == n && j == m) {
return true;
}
int k = i + j;
if (i < n && s1[i] == s3[k] && go(i + 1, j, s1, s2, s3)) {
return true;
}
if (j < m && s2[j] == s3[k] && go(i, j + 1, s1, s2, s3)) {
return true;
}
return false;
}
};JavaScriptTested in our runner
/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
const n = s1.length, m = s2.length;
if (n + m !== s3.length) return false;
const go = (i, j) => {
if (i === n && j === m) return true;
const k = i + j;
if (i < n && s1[i] === s3[k] && go(i + 1, j)) return true;
if (j < m && s2[j] === s3[k] && go(i, j + 1)) return true;
return false;
};
return go(0, 0);
};GoTested in our runner
func isInterleave(s1 string, s2 string, s3 string) bool {
n, m := len(s1), len(s2)
if n+m != len(s3) {
return false
}
var dfs func(i, j int) bool
dfs = func(i, j int) bool {
if i == n && j == m {
return true
}
k := i + j
if i < n && s1[i] == s3[k] && dfs(i+1, j) {
return true
}
if j < m && s2[j] == s3[k] && dfs(i, j+1) {
return true
}
return false
}
return dfs(0, 0)
}C#Tested in our runner
public class Solution {
public bool isInterleave(string s1, string s2, string s3) {
if (s1.Length + s2.Length != s3.Length) {
return false;
}
return Go(0, 0, s1, s2, s3);
}
private bool Go(int i, int j, string s1, string s2, string s3) {
if (i == s1.Length && j == s2.Length) {
return true;
}
int k = i + j;
if (i < s1.Length && s1[i] == s3[k] && Go(i + 1, j, s1, s2, s3)) {
return true;
}
if (j < s2.Length && s2[j] == s3[k] && Go(i, j + 1, s1, s2, s3)) {
return true;
}
return false;
}
}Approach 2: Memoized recursion
What's slow: the brute force reaches the same (i, j) through many different move orders, and each visit redoes the full search below that cell. There are only (n + 1) * (m + 1) distinct cells, but exponentially many paths into them.
The insight that fixes it: whether you can finish from (i, j) depends only on i and j, not on how you got there. So the first time a cell fails, record it. Any later visit returns false immediately. You only need to store failures, because the first success returns true all the way up the stack.
Steps
- Return false if the length check
n + m == len(s3)fails. - Create a boolean table
failedof size(n + 1) * (m + 1), all false. - Define
go(i, j)as in the brute force, but return false at once iffailed[i][j]is set. - If
i == nandj == m, return true. - Try the
s1move, then thes2move, each only when the character matchess3[i + j]. - If neither move leads to true, set
failed[i][j] = trueand return false.
Dry run
Trace on s1 = "", s2 = "hello", s3 = "hello". The table failed has 1 row and 6 columns, all false.
go(0, 0)callsgo(0, 1), which callsgo(0, 2), and so on down togo(0, 5).go(0, 5)hasi == nandj == m, so it returns true.- No cell ever fails, so
failedstays all false and each cell is visited once.
The answer is true. On this input the cache never fires. It matters on inputs like s1 = "aa", s2 = "aa", s3 = "aaab", where the cell (1, 1) is reached from both (0, 1) and (1, 0), fails once, and is skipped the second time.
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(n * m) |
Let n and m be the lengths of s1 and s2. A cell (i, j) can only run its two child calls the first time it is entered, because a failure is stored and a success ends the whole search. So at most (n + 1) * (m + 1) cells each do O(1) work, giving O(n * m) time. The failed table holds (n + 1) * (m + 1) booleans, and the recursion adds at most n + m frames, so space is O(n * m).
PythonTested in our runner
from typing import List, Optional
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m = len(s1), len(s2)
if n + m != len(s3):
return False
failed = [[False] * (m + 1) for _ in range(n + 1)]
def go(i: int, j: int) -> bool:
if i == n and j == m:
return True
if failed[i][j]:
return False
k = i + j
if i < n and s1[i] == s3[k] and go(i + 1, j):
return True
if j < m and s2[j] == s3[k] and go(i, j + 1):
return True
failed[i][j] = True # remember the dead end
return False
return go(0, 0)JavaTested in our runner
import java.util.*;
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int n = s1.length(), m = s2.length();
if (n + m != s3.length()) {
return false;
}
boolean[][] failed = new boolean[n + 1][m + 1];
return go(0, 0, s1, s2, s3, failed);
}
private boolean go(int i, int j, String s1, String s2, String s3, boolean[][] failed) {
if (i == s1.length() && j == s2.length()) {
return true;
}
if (failed[i][j]) {
return false;
}
int k = i + j;
if (i < s1.length() && s1.charAt(i) == s3.charAt(k) && go(i + 1, j, s1, s2, s3, failed)) {
return true;
}
if (j < s2.length() && s2.charAt(j) == s3.charAt(k) && go(i, j + 1, s1, s2, s3, failed)) {
return true;
}
failed[i][j] = true;
return false;
}
};C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n = s1.size(), m = s2.size();
if (n + m != (int)s3.size()) {
return false;
}
vector<vector<bool>> failed(n + 1, vector<bool>(m + 1, false));
return go(0, 0, s1, s2, s3, failed);
}
private:
bool go(int i, int j, const string& s1, const string& s2, const string& s3,
vector<vector<bool>>& failed) {
int n = s1.size(), m = s2.size();
if (i == n && j == m) {
return true;
}
if (failed[i][j]) {
return false;
}
int k = i + j;
if (i < n && s1[i] == s3[k] && go(i + 1, j, s1, s2, s3, failed)) {
return true;
}
if (j < m && s2[j] == s3[k] && go(i, j + 1, s1, s2, s3, failed)) {
return true;
}
failed[i][j] = true;
return false;
}
};JavaScriptTested in our runner
/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
const n = s1.length, m = s2.length;
if (n + m !== s3.length) return false;
const failed = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(false));
const go = (i, j) => {
if (i === n && j === m) return true;
if (failed[i][j]) return false;
const k = i + j;
if (i < n && s1[i] === s3[k] && go(i + 1, j)) return true;
if (j < m && s2[j] === s3[k] && go(i, j + 1)) return true;
failed[i][j] = true; // remember the dead end
return false;
};
return go(0, 0);
};GoTested in our runner
func isInterleave(s1 string, s2 string, s3 string) bool {
n, m := len(s1), len(s2)
if n+m != len(s3) {
return false
}
failed := make([][]bool, n+1)
for i := range failed {
failed[i] = make([]bool, m+1)
}
var dfs func(i, j int) bool
dfs = func(i, j int) bool {
if i == n && j == m {
return true
}
if failed[i][j] {
return false
}
k := i + j
if i < n && s1[i] == s3[k] && dfs(i+1, j) {
return true
}
if j < m && s2[j] == s3[k] && dfs(i, j+1) {
return true
}
failed[i][j] = true
return false
}
return dfs(0, 0)
}C#Tested in our runner
public class Solution {
public bool isInterleave(string s1, string s2, string s3) {
int n = s1.Length, m = s2.Length;
if (n + m != s3.Length) {
return false;
}
bool[,] failed = new bool[n + 1, m + 1];
return Go(0, 0, s1, s2, s3, failed);
}
private bool Go(int i, int j, string s1, string s2, string s3, bool[,] failed) {
if (i == s1.Length && j == s2.Length) {
return true;
}
if (failed[i, j]) {
return false;
}
int k = i + j;
if (i < s1.Length && s1[i] == s3[k] && Go(i + 1, j, s1, s2, s3, failed)) {
return true;
}
if (j < s2.Length && s2[j] == s3[k] && Go(i, j + 1, s1, s2, s3, failed)) {
return true;
}
failed[i, j] = true;
return false;
}
}
Solution pattern
2D Array (Unique Paths on Grid)
Approach 3: Bottom-up DP with one rowOptimal2D Array (Unique Paths on Grid)
What's slow: memoized recursion is already O(n * m) in time, but it stores a full table and pays for recursion frames. A cell only ever depends on the cell above it and the cell to its left.
The insight that fixes it: define dp[i][j] as true when the first i characters of s1 and the first j of s2 can form the first i + j of s3. Then dp[i][j] is true if dp[i-1][j] is true and s1[i-1] == s3[i+j-1], or dp[i][j-1] is true and s2[j-1] == s3[i+j-1]. Fill rows top to bottom, left to right. Row i needs only row i - 1, so one array indexed by j is enough.
When you reach dp[j] in row i, the old value of dp[j] is the cell above. The value at dp[j - 1] was already overwritten in this row, so it is the cell to the left.
Why it is correct. Every valid way to build the first i + j characters of s3 ends with a character taken from s1 or from s2. So dp[i][j] is true exactly when one of those two previous cells is true and its next character matches. Taking the OR of both cases never drops a valid path.
Steps
- Return false if
n + m != len(s3). - Create
dpof lengthm + 1, all false, and setdp[0] = truefor the empty prefixes. - For each
ifrom 0 tonand eachjfrom 0 tom, skip(0, 0). - Let
k = i + j - 1, the index ins3of the character just placed. - Set
okto true ifi > 0,dp[j]is true ands1[i-1] == s3[k](move down from the old value). - Also set
okto true ifj > 0,dp[j-1]is true ands2[j-1] == s3[k](move right from the new value). - Store
dp[j] = ok, and after all rows returndp[m].
Dry run
Trace on s1 = "", s2 = "hello", s3 = "hello". Here n = 0, m = 5, and only row i = 0 runs. Start with dp = [T, F, F, F, F, F].
| Step | i | j | k = i + j - 1 | Check | dp after |
|---|---|---|---|---|---|
| 1 | 0 | 0 | none | skip start cell | [T, F, F, F, F, F] |
| 2 | 0 | 1 | 0 | dp[0] is T and s2[0] = h equals s3[0] = h | [T, T, F, F, F, F] |
| 3 | 0 | 2 | 1 | dp[1] is T and s2[1] = e equals s3[1] = e | [T, T, T, F, F, F] |
| 4 | 0 | 3 | 2 | dp[2] is T and s2[2] = l equals s3[2] = l | [T, T, T, T, F, F] |
| 5 | 0 | 4 | 3 | dp[3] is T and s2[3] = l equals s3[3] = l | [T, T, T, T, T, F] |
| 6 | 0 | 5 | 4 | dp[4] is T and s2[4] = o equals s3[4] = o | [T, T, T, T, T, T] |
The loop ends and dp[5] is true, so the answer is true. Because i is 0 in every step, the "move down" check is skipped and only the left neighbour counts.
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(m) |
Let n and m be the lengths of s1 and s2. The two nested loops run (n + 1) * (m + 1) times, and each iteration does a constant number of comparisons, so time is O(n * m). The only extra structure is the array dp of m + 1 booleans, so space is O(m). Choosing s2 as the shorter string makes that O(min(n, m)).
PythonTested in our runner
from typing import List, Optional
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m = len(s1), len(s2)
if n + m != len(s3):
return False
dp = [False] * (m + 1)
dp[0] = True
for i in range(n + 1):
for j in range(m + 1):
if i == 0 and j == 0:
continue
k = i + j - 1 # index in s3 of the character just placed
ok = False
# old dp[j] is the cell above: last char came from s1
if i > 0 and dp[j] and s1[i - 1] == s3[k]:
ok = True
# dp[j - 1] is already this row: last char came from s2
if j > 0 and dp[j - 1] and s2[j - 1] == s3[k]:
ok = True
dp[j] = ok
return dp[m]JavaTested in our runner
import java.util.*;
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int n = s1.length(), m = s2.length();
if (n + m != s3.length()) {
return false;
}
boolean[] dp = new boolean[m + 1];
dp[0] = true;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 && j == 0) {
continue;
}
int k = i + j - 1;
boolean ok = false;
if (i > 0 && dp[j] && s1.charAt(i - 1) == s3.charAt(k)) {
ok = true;
}
if (j > 0 && dp[j - 1] && s2.charAt(j - 1) == s3.charAt(k)) {
ok = true;
}
dp[j] = ok;
}
}
return dp[m];
}
};C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int n = s1.size(), m = s2.size();
if (n + m != (int)s3.size()) {
return false;
}
vector<char> dp(m + 1, 0);
dp[0] = 1;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 && j == 0) {
continue;
}
int k = i + j - 1;
bool ok = false;
if (i > 0 && dp[j] && s1[i - 1] == s3[k]) {
ok = true;
}
if (j > 0 && dp[j - 1] && s2[j - 1] == s3[k]) {
ok = true;
}
dp[j] = ok;
}
}
return dp[m];
}
};JavaScriptTested in our runner
/**
* @param {string} s1
* @param {string} s2
* @param {string} s3
* @return {boolean}
*/
var isInterleave = function(s1, s2, s3) {
const n = s1.length, m = s2.length;
if (n + m !== s3.length) return false;
const dp = new Array(m + 1).fill(false);
dp[0] = true;
for (let i = 0; i <= n; i++) {
for (let j = 0; j <= m; j++) {
if (i === 0 && j === 0) continue;
const k = i + j - 1; // index in s3 of the character just placed
let ok = false;
if (i > 0 && dp[j] && s1[i - 1] === s3[k]) ok = true;
if (j > 0 && dp[j - 1] && s2[j - 1] === s3[k]) ok = true;
dp[j] = ok;
}
}
return dp[m];
};GoTested in our runner
func isInterleave(s1 string, s2 string, s3 string) bool {
n, m := len(s1), len(s2)
if n+m != len(s3) {
return false
}
dp := make([]bool, m+1)
dp[0] = true
for i := 0; i <= n; i++ {
for j := 0; j <= m; j++ {
if i == 0 && j == 0 {
continue
}
k := i + j - 1
ok := false
if i > 0 && dp[j] && s1[i-1] == s3[k] {
ok = true
}
if j > 0 && dp[j-1] && s2[j-1] == s3[k] {
ok = true
}
dp[j] = ok
}
}
return dp[m]
}C#Tested in our runner
public class Solution {
public bool isInterleave(string s1, string s2, string s3) {
int n = s1.Length, m = s2.Length;
if (n + m != s3.Length) {
return false;
}
bool[] dp = new bool[m + 1];
dp[0] = true;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0 && j == 0) {
continue;
}
int k = i + j - 1;
bool ok = false;
if (i > 0 && dp[j] && s1[i - 1] == s3[k]) {
ok = true;
}
if (j > 0 && dp[j - 1] && s2[j - 1] == s3[k]) {
ok = true;
}
dp[j] = ok;
}
}
return dp[m];
}
}Common mistakes
- Skipping the
len(s1) + len(s2) != len(s3)check. Without it the indexi + j - 1can run past the end ofs3, or the table can report true for a string of the wrong length. Return false immediately when the lengths differ. - Using
s3[i - 1]ors3[j - 1]as the target in the DP. A cell(i, j)has placedi + jcharacters, so the last one iss3[i + j - 1]. Computek = i + j - 1once per cell. - Greedy matching, such as
if s1[i] == s3[k]: take s1. Withs1 = "ab",s2 = "ac",s3 = "acab", greedy takesafroms1, then gets stuck onc. The answer is true by takingacfroms2first, so you must keep both options alive. - Initializing the first row or column to true without checking characters.
dp[0][j]must require thats2[0..j-1]equalss3[0..j-1]. In the loop version above this happens naturally because every cell goes through the same two checks. - Filling the 1D array from right to left. Then
dp[j - 1]still holds the previous row, and the move from the left reads stale data. Iteratejupward sodp[j - 1]is already this row's value. - Overwriting
dp[0]wrongly in later rows. In rowi > 0,dp[0]must becomedp[0] and s1[i-1] == s3[i-1]. The unified loop does this, because forj = 0only thes1check can fire.
Edge cases
s1 = "",s2 = "",s3 = "": both strings are empty ands3is empty, so the answer is true. The start cell is the goal cell.s1 = "",s2 = "hello",s3 = "hello": only one source is available, so the answer is true. Withs3 = "hellp"it is false.- Length mismatch such as
s1 = "a",s2 = "b",s3 = "abc": return false before touching the table. s1 = "ab",s2 = "ba",s3 = "bbaa": the letter counts match but no valid order exists, so the answer is false. Counting letters alone is not enough.s1 = "aa",s2 = "aa",s3 = "aaaa": every cell matches and many paths reach the same cell. The answer is true, and this is the shape that blows up the brute force.- Both strings 100 characters of
aands3is 199afollowed byb: this is the adversarial case for unmemoized recursion. The answer is false, and the DP handles it in about 10,000 cell updates.
Follow-ups interviewers ask
- Can you reduce the extra space below O(n * m)?
- Yes, and the third approach already does. Row i only reads row i - 1 and the cell to its left, so one array of length m + 1 is enough. If you want the smaller array, swap the strings so that s2 is the shorter one. That gives O(min(n, m)) space with the same O(n * m) time.
- How would you return an actual interleaving instead of true or false?
- Keep the full (n + 1) by (m + 1) table, since the one-row version overwrites the history you need. Start at the goal cell (n, m) and walk back. At (i, j), if dp[i-1][j] is true and s1[i-1] equals s3[i+j-1], the last character came from s1 and you step up. Otherwise step left and use s2. Reverse the recorded choices at the end.
- How does this change with three source strings?
- The state becomes (i, j, l), the counts taken from each string, and the target index is i + j + l. The table grows to (n + 1) * (m + 1) * (p + 1) cells, each with up to three transitions. Time and space are O(n * m * p). With k strings the state space grows as the product of all lengths, so it does not scale to large k.
Interleaving String FAQ
What is the time complexity of Interleaving String?
The DP solution runs in O(n * m) time, where n and m are the lengths of s1 and s2. It fills (n + 1) * (m + 1) cells with constant work each. Plain recursion without caching is O(2^(n + m)). The 1D version uses O(m) space.
Why use dynamic programming for Interleaving String?
Whether the rest of s3 can be built depends only on how many characters you took from s1 and from s2, which is the pair (i, j). Many move orders reach the same pair, so the same subproblem repeats exponentially often. DP computes each of the (n + 1) * (m + 1) pairs once. A greedy choice cannot work, because when both strings match the current character you cannot know which one to take.
Why does the check len(s1) + len(s2) == len(s3) come first?
Every character of both strings must be used exactly once, so any valid s3 has exactly that length. If the lengths differ, the answer is false with no further work. The check also guarantees that the index i + j - 1 never leaves s3 inside the DP.
Can Interleaving String be solved in O(1) extra space?
No known approach does it in general. The answer depends on many (i, j) states, and you must remember which ones are reachable. The best practical bound is O(min(n, m)) extra space with the one-row DP, since you only need the previous row.
Is there a bit manipulation solution for Interleaving String?
One exists in principle: each of the n + m positions of s3 is assigned to s1 or s2, which is a bitmask with exactly n ones. Checking all such masks is the brute force in disguise and takes exponential time. The DP over (i, j) is the efficient version of the same idea.
Can I write Interleaving String in Python or Java with the same approach?
Yes, the DP is identical in every language. The loops, the index k = i + j - 1 and the two checks do not change. In Java, C# and Go, index strings by position and watch that i - 1 and j - 1 are used only when i and j are positive.
Asked at
See which companies ask this — Pro
Related problems
- Unique Paths · same technique: 2D Array (Unique Paths on Grid)
- Minimum Path Sum · same technique: 2D Array (Unique Paths on Grid)
- Unique Paths II · same technique: 2D Array (Unique Paths on Grid)
- Maximal Square · same technique: 2D Array (Unique Paths on Grid)
- Triangle · same technique: 2D Array (Unique Paths on Grid)
- Distinct Subsequences · next harder, same pattern
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns