13. Interleaved Strings
β GFG solution to the Interleaved Strings problem: determine if string s3 is formed by interleaving s1 and s2 while maintaining character order using dynamic programming. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.
Interleaving of two strings s1 and s2 is a way to mix their characters to form a new string s3, while maintaining the relative order of characters from s1 and s2.
Conditions for interleaving:
Characters from
s1must appear in the same order ins3as they are ins1.Characters from
s2must appear in the same order ins3as they are ins2.The length of
s3must be equal to the combined length ofs1ands2.
π Examples
Example 1
Input: s1 = "AAB", s2 = "AAC", s3 = "AAAABC"
Output: true
Explanation: The string "AAAABC" has all characters of the other two strings and in the same order.Example 2
Example 3
π Constraints
$1 \le \text{s1.length, s2.length} \le 300$
$1 \le \text{s3.length} \le 600$
β
My Approach
The optimal approach uses Dynamic Programming with Space Optimization to efficiently determine if s3 can be formed by interleaving s1 and s2:
1D Dynamic Programming (Space Optimized)
Initial Check:
Verify if the total length of
s1ands2equals the length ofs3. If not, return false immediately.
DP Array Setup:
Use a 1D boolean array
dpof sizem+1(wheremis the length ofs2).dp[j]represents whether the firsticharacters ofs1and firstjcharacters ofs2can interleave to form the firsti+jcharacters ofs3.
Base Case:
dp[0] = true(empty strings can interleave to form empty string).Initialize first row: Check if
s2alone can form the beginning ofs3.
DP Transition:
For each position
(i, j), check two possibilities:Take character from
s1:dp[j]remains true if previous state was true AND currents1character matchess3.Take character from
s2:dp[j-1]was true AND currents2character matchess3.
Update
dp[j]using OR logic of both possibilities.
Result:
Return
dp[m]which indicates if entires1ands2can interleave to forms3.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ m), where n is the length of
s1and m is the length ofs2. We fill a DP table of size n Γ m, processing each cell once.Expected Auxiliary Space Complexity: O(m), as we use a 1D array of size m+1 for space-optimized dynamic programming, avoiding the O(n Γ m) space of a full 2D DP table.
π§βπ» Code (C++)
β‘ View Alternative Approaches with Code and Analysis
π 2οΈβ£ BFS Queue-Based Approach
π‘ Algorithm Steps:
Use breadth-first search to explore all possible interleaving paths.
Track visited states using a set to avoid redundant computation.
Each state represents current positions in both strings.
Return true if we successfully reach the end of all strings.
π Complexity Analysis:
Time: β±οΈ O(nΓm) - Visit each state at most once
Auxiliary Space: πΎ O(nΓm) - Queue and visited set storage
β
Why This Approach?
Intuitive path exploration visualization
Natural state transition tracking
Easy to debug and trace execution flow
Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1010/1111 test cases due to time constraints).
π 3οΈβ£ Recursive Memoization (Top-Down DP)
π‘ Algorithm Steps:
Use recursion to try both choices at each position.
Cache results in a memoization map to avoid recomputation.
Base cases handle when either string is exhausted.
Combine results from taking character from either string.
π Complexity Analysis:
Time: β±οΈ O(nΓm) - Each subproblem computed once
Auxiliary Space: πΎ O(nΓm) - Recursion stack and memoization map
β
Why This Approach?
Top-down thinking matches problem intuition
Easy to convert from naive recursion
Good for explaining DP concept in interviews
π 4οΈβ£ 2D Bottom-Up DP
π‘ Algorithm Steps:
Create a 2D DP table where dp[i][j] represents if first i chars of s1 and j chars of s2 interleave to form first i+j chars of s3.
Initialize base case for empty strings.
Fill first row and column for single string matches.
Fill remaining cells using transition from previous states.
π Complexity Analysis:
Time: β±οΈ O(nΓm) - Fill entire DP table once
Auxiliary Space: πΎ O(nΓm) - 2D DP table storage
β
Why This Approach?
Complete state visibility for debugging
Classic DP pattern implementation
Foundation for space-optimized version
π π Comparison of Approaches
π Approach
β±οΈ Time Complexity
πΎ Space Complexity
β Pros
β οΈ Cons
π·οΈ 1D DP (Space Optimized)
π’ O(nΓm)
π’ O(m)
π Optimal space usage
π§ Less intuitive state tracking
π BFS Queue-Based
π’ O(nΓm)
π‘ O(nΓm)
π Clear path visualization
β οΈ TLE on large inputs
π Recursive Memoization
π’ O(nΓm)
π‘ O(nΓm)
π― Natural problem decomposition
π Stack overflow risk for large inputs
π 2D Bottom-Up DP
π’ O(nΓm)
π‘ O(nΓm)
β Easy to understand and verify
πΎ Uses more space than needed
π Best Choice Recommendation
π― Scenario
ποΈ Recommended Approach
π₯ Performance Rating
π Production/Optimal performance
π₯ 1D DP Space Optimized
β β β β β
π Learning/Interview explanation
π₯ 2D Bottom-Up DP
β β β β β
π§ Debugging complex cases
π₯ Recursive Memoization
β β β β β
π― Understanding state transitions
π BFS Queue-Based
β β β ββ
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated