Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)?

Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)?
def inter(s1, s2, s3):
    if len(s1) + len(s2) != len(s3): return False
    dp = [[False] * (len(s2) + 1) for _ in range(len(s1) + 1)]
    dp[0][0] = True
    for i in range(len(s1) + 1):
        for j in range(len(s2) + 1):
            if i and s1[i-1] == s3[i+j-1] and dp[i-1][j]: dp[i][j] = True
            if j and s2[j-1] == s3[i+j-1] and dp[i][j-1]: dp[i][j] = True
    return dp[-1][-1]
print(inter("aab", "axy", "aaxaby"), inter("aab", "axy", "abaaxy"))
What is printed?
  1. A. True True
  2. B. False True
  3. C. False False
  4. D. True False

Correct answer: D. True False

'aaxaby' = a(s1) a(s2) x(s2) a(s1) b(s1) y(s2). 'abaaxy' fails: its 'b' comes second, but s1's b needs both of s1's a's first and s2 has no b. The DP tries every split, so a greedy choice of which string's 'a' to use cannot mislead it.

More Coding Interview Problems questions

Exams that ask this topic