AlgoMaster Logo

Interleaving String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The recursive approach attempts to build the interleaved string one character at a time. At each step, we decide whether to take the next character from s1 or s2, and check recursively if taking that character leads to a solution. If both choices are possible, we try both.

Steps:

  1. Define a recursive function that takes three indices, one for each of s1s2, and s3.
  2. If both indices for s1 and s2 are at the start of their respective strings and s3 is also at the beginning, then s1 and s2 are interleaving s3.
  3. If the current character of s1 matches with s3, make a recursive call by incrementing the index of s1 and s3.
  4. If the current character of s2 matches with s3, make a recursive call by incrementing the index of s2 and s3.
  5. If either of the recursive calls return true, then s1 and s2 can interleave s3.

Code:

2. Memoization (Top-Down DP) Approach

Intuition:

The recursive solution recalculates solutions for overlapping subproblems, leading to inefficiencies. By storing previously calculated results in a 2D array, we can optimize the recursive solution using memoization.

Steps:

  1. Use a 2D array memo where memo[i][j] indicates whether s1[i:] and s2[j:] can interleave into s3[i+j:].
  2. Follow the same logic as the recursive approach, but store results in memo before making recursive calls, and check memo before calculating new results.

Code:

3. Iterative Dynamic Programming Approach

Intuition:

Transforming the recursive approach into an iterative form using a 2D boolean array can avoid the function call overhead.

Steps:

  1. Create a 2D boolean array dp where dp[i][j] is true if s1[0:i] and s2[0:j] can interleave into s3[0:i+j].
  2. Initialize dp[0][0] to true because empty strings interleave to make an empty string.
  3. Iterate over s1 and s2 and fill dp based on previous results.
  4. Return dp[m][n].

Code: