Interleaving String
Master this topic with zero to advance depth.
Interleaving String
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 they are divided into non-empty substrings such that:
s = s1 + s2 + ... + snt = t1 + t2 + ... + tm- The interleaving is
s1 + t1 + s2 + t2 + s3 + t3 + ...ort1 + s1 + t2 + s2 + t3 + s3 + ...
Visual Representation
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Characters from s1 (bold), s2 (italic):
a a d b b c b c a c
(a)(a)(d)(b)(b)(c)(b)(c)(a)(c)
s1 s1 s2 s2 s2 s1 s2 s1 s2 s1
Result: TrueExamples
Level I: Dynamic Programming (Bottom-Up 2D)
Intuition
We use a 2D table dp[i][j] to represent if s3[0...i+j-1] is formed by interleaving s1[0...i-1] and s2[0...j-1].
Thought Process
dp[i][j]is true if:dp[i-1][j]is true ANDs1[i-1] == s3[i+j-1]- OR
dp[i][j-1]is true ANDs2[j-1] == s3[i+j-1]
- Base case:
dp[0][0] = true. - Base case:
dp[i][0]matches only againsts1.dp[0][j]matches only againsts2.
Detailed Dry Run
s1="a", s2="b", s3="ab"
| i\j | "" | 'b' |
|---|---|---|
| "" | T | F (s2[0]!=s3[0]) |
| 'a' | T (s1[0]==s3[0]) | T (s1[0]==s3[0] or s2[0]==s3[1]) |
| Result: True |
Level II: Memoization (Top-Down 2D)
Intuition
The 2D DP bottom-up approach fills the entire table. Top-down memoization only explores reachable states. Both have the same asymptotic complexity.
Visual
s1="a", s2="b", s3="ab"
solve(0,0): s1[0]='a'==s3[0] -> solve(1,0)
or s2[0]='b'!=s3[0] -> blocked
solve(1,0): s2[0]='b'==s3[1] -> solve(1,1)=TrueDetailed Dry Run
s1="a", s2="b", s3="ab". solve(0,0): 'a'=='a' -> solve(1,0). solve(1,0): 'b'=='b' -> solve(1,1)=True.
Level III: Space Optimized (1D)
Intuition
Like most 2D matrix DP problems where dp[i][j] only depends on dp[i-1][j] and dp[i][j-1], we can reduce space to O(M) (where M is length of s2).
Logic Steps
- Initialize a
dparray of sizes2.length + 1. - In the outer loop (s1),
dp[j]will representdp[i][j]. dp[j]is updated as(dp[j] && s1[i-1] == s3[i+j-1]) || (dp[j-1] && s2[i-1] == s3[i+j-1]).
Detailed Dry Run
Same logic, but we only keep one row. The 'up' dependency comes from the array value before modification, and 'left' dependency comes from the array value after modification (current row).
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.