Data Structures & AlgorithmsVery hardProduct company OA

Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can form c[:i+j].

Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can form c[:i+j].
def interleave(a, b, c):
    if len(a) + len(b) != len(c): return False
    dp = [[False] * (len(b) + 1) for _ in range(len(a) + 1)]
    dp[0][0] = True
    for i in range(len(a) + 1):
        for j in range(len(b) + 1):
            if i and a[i - 1] == c[i + j - 1] and dp[i - 1][j]: dp[i][j] = True
            if j and b[j - 1] == c[i + j - 1] and dp[i][j - 1]: dp[i][j] = True
    return dp[-1][-1]
print(interleave("abc", "abd", "aabdbc"), interleave("abc", "abd", "abadcb"), interleave("ab", "ab", "abab"))
What is printed?
  1. A. False False True
  2. B. True True True
  3. C. True False True
  4. D. True False False

Correct answer: C. True False True

Greedy matching fails when both strings offer the same next letter, so the DP tries both. "aabdbc" = a(a) a(b) b(b) d(b) b(a) c(a) → True. "abadcb": 'c' would have to come before a's 'b', breaking a's order → False. "abab" works several ways. O(|a|·|b|).

More Coding Interview Problems questions

Exams that ask this topic