#97

Interleaving String

Medium
StringDynamic ProgrammingDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(n * m)
💡

Intuition

Time O(n * m)Space O(n * m)

The optimal solution uses dynamic programming to build a table that keeps track of whether substrings of s1 and s2 can form substrings of s3. This avoids redundant calculations and improves efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a 2D DP array where dp[i][j] indicates if s3 up to index i + j can be formed by interleaving s1 up to index i and s2 up to index j.
  2. 2Step 2: Initialize the DP array with base cases: dp[0][0] = true, and fill in the first row and column based on matches with s3.
  3. 3Step 3: Fill the DP table by checking if the current character from s1 or s2 matches the current character in s3.
solution.py12 lines
1def isInterleave(s1, s2, s3):
2    if len(s1) + len(s2) != len(s3): return False
3    dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
4    dp[0][0] = True
5    for j in range(1, len(s2) + 1):
6        dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]
7    for i in range(1, len(s1) + 1):
8        dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]
9    for i in range(1, len(s1) + 1):
10        for j in range(1, len(s2) + 1):
11            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])
12    return dp[len(s1)][len(s2)]

Complexity note: The time complexity is O(n * m) because we fill a 2D DP table where n and m are the lengths of s1 and s2. The space complexity is also O(n * m) due to the storage of the DP table.

  • 1Understanding the interleaving concept is crucial; it requires matching characters from both strings in a specific order.
  • 2Dynamic programming is a powerful technique for problems involving combinations and sequences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.