sagelearnai

Interleaving String

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #97

Return true if s3 can be formed by interleaving s1 and s2, merging them while keeping each string's own character order.

Examples

text
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"  →  true
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"  →  false
s1 = "", s2 = "", s3 = ""                      →  true

Hints

  1. Greedy fails when the next character matches both strings.
  2. The state is how many characters you've used from each string: (i, j). The next character of s3 is then s3[i+j].

Approach

If len(s1) + len(s2) != len(s3), return false. dp[i][j] is true when s3[:i+j] can be formed from s1[:i] and s2[:j]:

text
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])

A 1-D rolling array over j gives O(len(s2)) space, which is the follow-up the problem asks for. The time is O(m·n).

Complexity

Time: O(m·n). Space: O(n).

Python solution
def isInterleave(s1, s2, s3):
    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
            else:
                up = dp[j] and i > 0 and s1[i - 1] == s3[i + j - 1]
                left = j > 0 and dp[j - 1] and s2[j - 1] == s3[i + j - 1]
                dp[j] = up or left
    return dp[n]
JavaScript solution
function isInterleave(s1, s2, s3) {
  const m = s1.length, n = s2.length;
  if (m + n !== s3.length) return false;
  const dp = new Array(n + 1).fill(false);
  for (let i = 0; i <= m; i++) for (let j = 0; j <= n; j++) {
    if (!i && !j) { dp[j] = true; continue; }
    const up = i > 0 && dp[j] && s1[i - 1] === s3[i + j - 1];
    const left = j > 0 && dp[j - 1] && s2[j - 1] === s3[i + j - 1];
    dp[j] = up || left;
  }
  return dp[n];
}