Interleaving String - Problem

Given strings s1, s2, and s3, determine 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 substrings such that:

  • s = s1 + s2 + ... + sn
  • t = t1 + t2 + ... + tm
  • |n - m| ≤ 1

The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

Note: a + b is the concatenation of strings a and b.

Input & Output

Example 1 — Valid Interleaving
$ Input: s1 = "aab", s2 = "axy", s3 = "aaxaby"
Output: true
💡 Note: We can form s3 by taking: a(s1) + a(s2) + a(s1) + x(s2) + b(s1) + y(s2) = "aaxaby"
Example 2 — Invalid Interleaving
$ Input: s1 = "aab", s2 = "axy", s3 = "aabcxy"
Output: false
💡 Note: Character 'c' appears in s3 but not in s1 or s2, so interleaving is impossible
Example 3 — Empty String Cases
$ Input: s1 = "", s2 = "", s3 = ""
Output: true
💡 Note: Empty strings can form an empty string by interleaving

Constraints

  • 0 ≤ s1.length, s2.length ≤ 100
  • 0 ≤ s3.length ≤ 200
  • s1, s2, and s3 consist of lowercase English letters

Visualization

Tap to expand
Interleaving String INPUT s1 = "aab" a a b s2 = "axy" a x y s3 = "aaxaby" a a x a b y Legend: from s1 from s2 s3 len(s1) + len(s2) = len(s3) 3 + 3 = 6 [OK] ALGORITHM STEPS 1 Create DP Table dp[i][j] = can form s3[0..i+j-1] 2 Initialize Base dp[0][0] = true 3 Fill DP Table Check s1[i-1] or s2[j-1] 4 Return Result dp[m][n] is the answer DP Table (4x4): "" a x y "" T F F F a T T F F a T F T F b F F T T dp[3][3] = T (answer) FINAL RESULT Valid Interleaving Found: a s1[0] a s2[0] x s2[1] a s1[1] b s1[2] y s2[2] Output: true Sequence from s1: a, a, b Sequence from s2: a, x, y Interleaved order: s1[0] + s2[0] + s2[1] + s1[1] + s1[2] + s2[2] = "aaxaby" [OK] Time: O(m*n), Space: O(m*n) Key Insight: dp[i][j] = true if s3[0..i+j-1] can be formed using s1[0..i-1] and s2[0..j-1]. Transition: dp[i][j] = (dp[i-1][j] AND s1[i-1]==s3[i+j-1]) OR (dp[i][j-1] AND s2[j-1]==s3[i+j-1]) We check if current char in s3 matches char from s1 or s2, maintaining relative order within each. TutorialsPoint - Interleaving String | Dynamic Programming Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
180.0K Views
Medium Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen