SDE & MLE Prep

97. Interleaving String

Problem

Decide whether s3 can be formed by interleaving s1 and s2: splitting both into pieces and alternating them while keeping the characters of each in their original order.

Example: s1 = "aabcc", s2 = "dbbca": s3 = "aadbbcbcac" → true; s3 = "aadbbbaccc" → false

Constraints: follow-up: O(len(s2)) extra space.

dp[i][j] = s3[:i+j] is an interleaving of s1[:i] and s2[:j]: true if (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]).

Complexity: O(m·n).

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        m, n = len(s1), len(s2)
        if m + n != len(s3):
            return False
        dp = [False] * (n + 1)
        for i in range(m + 1):
            for j in range(n + 1):
                if i == 0 and j == 0:
                    dp[j] = True
                    continue
                from_s1 = i > 0 and dp[j] and s1[i - 1] == s3[i + j - 1]
                from_s2 = j > 0 and dp[j - 1] and s2[j - 1] == s3[i + j - 1]
                dp[j] = from_s1 or from_s2
        return dp[n]