97. Interleaving String
mediumDecide whether s3 is formed by interleaving s1 and s2 — preserving order within each. A natural 2D DP where dp[i][j] tracks whether the first i chars of s1 and first j chars of s2 can be interleaved into the first i+j chars of s3.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that: s = s1 + s2 + ... + sn, t = t1 + t2 + ... + tm, |n - m| <= 1, and the interleaving is s1 + t1 + s2 + t2 + ... or t1 + s1 + t2 + s2 + .... Note: a + b is the concatenation of strings a and b.
Constraints
0 <= s1.length, s2.length <= 1000 <= s3.length <= 200s1, s2, and s3 consist of lowercase English letters.
Examples
Example 1
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"trueExplanation: One way to obtain s3 is: Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a". Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac". Since s3 can be obtained by interleaving s1 and s2, we return true.
Example 2
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"falseExplanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.
Example 3
s1 = "", s2 = "", s3 = ""trueSolve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
If len(s1) + len(s2) != len(s3), return false immediately.
Hint 2
dp[i][j] = can the first i chars of s1 and first j chars of s2 interleave to form the first i+j chars of s3?
Hint 3
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]).
Hint 4
Base case dp[0][0] = true.
Solution approach
Reveal approach
Bottom-up DP over a 2D boolean table dp[m+1][n+1]. dp[i][j] means the first i chars of s1 and first j chars of s2 can interleave to form the first i+j chars of s3. Initialize dp[0][0] = true; dp[i][0] = dp[i-1][0] AND s1[i-1] == s3[i-1]; dp[0][j] symmetric. For each i and j: dp[i][j] = (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]). Return dp[m][n]. Space optimization: only the previous row is needed — collapse to a 1D array of length n+1.
Complexity
- Time
- O(m * n)
- Space
- O(n)
Related patterns
- dynamic-programming
- string-dp
- two-strings-table
Related problems
- 72. Edit Distance
- 1143. Longest Common Subsequence
- 115. Distinct Subsequences
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
More 2D Dynamic Programming practice problems
- 5. Longest Palindromic Substring
- 10. Regular Expression Matching
- 44. Wildcard Matching
- 63. Unique Paths II
- 64. Minimum Path Sum
- 85. Maximal Rectangle
- 115. Distinct Subsequences
- 174. Dungeon Game