Interleaving String (LeetCode 97): Solution and Explanation
Given three strings, decide whether the third can be formed by weaving the first two together. The characters of each of the first two strings must appear in their original relative order, but you are free to choose at every position which string supplies the next character.
Watch it run step by step
Try your own input and write the code →Intuition
A natural first attempt is greedy: walk through s3 and take the next character from whichever of s1 or s2 matches. That fails when both match, because the right choice depends on what comes later. So you have to explore both options, and a plain recursion that branches whenever both strings match is exponential in the worst case.
The fix is to notice what actually defines the state of that recursion. If you have used i characters of s1 and j characters of s2, you must have produced exactly the first i + j characters of s3. Nothing else about the path matters. So there are only (m + 1) × (n + 1) states, and each can be solved once.
Define dp[i][j] as true when the first i characters of s1 and the first j of s2 can interleave into the first i + j characters of s3. The last character of that prefix, s3[i + j - 1], came either from s1 or from s2. If it came from s1, it must equal s1[i - 1] and dp[i - 1][j] must be true; if from s2, it must equal s2[j - 1] and dp[i][j - 1] must be true. Either is enough, and the answer sits in dp[m][n].
Approach: 2D bottom-up dynamic programming
- If
len(s1) + len(s2)differs fromlen(s3), return False immediately. - Allocate an (m + 1) by (n + 1) table of False and set
dp[0][0] = True, since two empty strings form an empty string. - Fill the first column:
dp[i][0]is true whendp[i-1][0]is true ands1[i-1] == s3[i-1], using onlys1. - Fill the first row the same way using only
s2. - For every other cell, set
dp[i][j]to true ifdp[i-1][j]is true ands1[i-1] == s3[i+j-1], or ifdp[i][j-1]is true ands2[j-1] == s3[i+j-1]. - Return
dp[m][n].
Step-by-step example
s1 = "ab", s2 = "c", s3 = "acb"
- The lengths add up, 2 + 1 = 3, so the table is 3 by 2 with
dp[0][0] = True. - First column:
dp[1][0]is True because 'a' matchess3[0].dp[2][0]is False because 'b' does not matchs3[1] = 'c'. - First row:
dp[0][1]is False because 'c' does not matchs3[0] = 'a'. dp[1][1]checkss3[1] = 'c'. Coming from above fails becausedp[0][1]is False, but coming from the left works becausedp[1][0]is True ands2[0] = 'c', so it is True.dp[2][1]checkss3[2] = 'b'. Coming from above works:dp[1][1]is True ands1[1] = 'b'. Sodp[2][1]is True and the answer is True.
Code: Python, Java, C++
1class Solution:
2 def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
3 m, n = len(s1), len(s2)
4 if m + n != len(s3):
5 return False
6
7 dp = [[False] * (n + 1) for _ in range(m + 1)]
8 dp[0][0] = True
9
10 # First column
11 for i in range(1, m + 1):
12 dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]
13
14 # First row
15 for j in range(1, n + 1):
16 dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]
17
18 # Fill DP table
19 for i in range(1, m + 1):
20 for j in range(1, n + 1):
21 dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[i+j-1]) or \
22 (dp[i][j-1] and s2[j-1] == s3[i+j-1])
23
24 return dp[m][n]1class Solution {
2 public boolean isInterleave(String s1, String s2, String s3) {
3 int m = s1.length(), n = s2.length();
4 if (m + n != s3.length()) return false;
5
6 boolean[][] dp = new boolean[m + 1][n + 1];
7 dp[0][0] = true;
8
9 for (int i = 1; i <= m; i++) dp[i][0] = dp[i-1][0] && s1.charAt(i-1) == s3.charAt(i-1);
10 for (int j = 1; j <= n; j++) dp[0][j] = dp[0][j-1] && s2.charAt(j-1) == s3.charAt(j-1);
11
12 for (int i = 1; i <= m; i++) {
13 for (int j = 1; j <= n; j++) {
14 dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1)) ||
15 (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
16 }
17 }
18
19 return dp[m][n];
20 }
21}1class Solution {
2public:
3 bool isInterleave(string s1, string s2, string s3) {
4 int m = s1.size(), n = s2.size();
5 if (m + n != s3.size()) return false;
6
7 vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
8 dp[0][0] = true;
9
10 for (int i = 1; i <= m; i++) dp[i][0] = dp[i-1][0] && s1[i-1] == s3[i-1];
11 for (int j = 1; j <= n; j++) dp[0][j] = dp[0][j-1] && s2[j-1] == s3[j-1];
12
13 for (int i = 1; i <= m; i++) {
14 for (int j = 1; j <= n; j++) {
15 dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i+j-1]) ||
16 (dp[i][j-1] && s2[j-1] == s3[i+j-1]);
17 }
18 }
19
20 return dp[m][n];
21 }
22};Time and space complexity
O(m × n)
Each of the (m + 1) × (n + 1) cells is computed once with at most two character comparisons.
O(m × n)
The full table is stored. Because each row only depends on the row above and the cell to the left, it can be reduced to a single row of length n + 1.
Other approaches
Recursion with memoization (time O(m × n), space O(m × n))
Recurse on (i, j), trying to consume the next character of s3 from either string, and cache each state's result. It is often the easiest way to derive the solution and skips unreachable states.
One-dimensional DP (time O(m × n), space O(n))
Keep a single array indexed by j and update it row by row, where dp[j] still holds the value from above and dp[j-1] holds the freshly updated value from the left.
Common mistakes
- Skipping the length check. Without it, the table can report True for an
s3that has extra characters at the end. - Using a greedy two-pointer scan. It fails on inputs where both strings offer the same next character and the wrong choice dead-ends later.
- Indexing
s3withi + jinstead ofi + j - 1. The cell (i, j) covers a prefix of length i + j, whose last character is at index i + j - 1. - Filling the first row and column without chaining on the previous cell. Once a prefix fails to match, every longer prefix along that edge must also be False.
Frequently asked questions
Why doesn't a greedy two-pointer approach work for Interleaving String?
When the next characters of s1 and s2 are the same, greedy has to pick one, and the wrong pick can make the rest impossible even though the other pick would succeed. Dynamic programming considers both possibilities at every state.
What does dp[i][j] mean in Interleaving String?
It says whether the first i characters of s1 and the first j characters of s2 can be interleaved to form exactly the first i + j characters of s3.
Can Interleaving String use O(n) space?
Yes. Each cell only needs the cell above and the cell to its left, so a single array of length n + 1 updated in place is enough.
What is the time complexity of Interleaving String?
It is O(m × n), where m and n are the lengths of s1 and s2, because there are that many prefix pairs and each is solved in constant time.