ProgrammingHardCapgemini · Infosys pattern

What will be the output of the following pseudocode (checking if s3 is an interleaving of s1 and s2, via dynamic programming)?

What will be the output of the following pseudocode (checking if s3 is an interleaving of s1 and s2, via dynamic programming)?
Function isInterleave(String s1, String s2, String s3)
    if (length(s1) + length(s2) != length(s3))
        return false
    end if
    Boolean dp[length(s1)+1][length(s2)+1] = all false
    dp[0][0] = true
    for (each i from 0 to length(s1))
        for (each j from 0 to length(s2))
            if (i > 0 and s1[i-1] == s3[i+j-1] and dp[i-1][j])
                dp[i][j] = true
            end if
            if (j > 0 and s2[j-1] == s3[i+j-1] and dp[i][j-1])
                dp[i][j] = true
            end if
        end for
    end for
    return dp[length(s1)][length(s2)]
End Function

Print isInterleave("ab", "cd", "acbd")
  1. A. false
  2. B. true
  3. C. Error: length mismatch
  4. D. null

Correct answer: B. true

'acbd' can be formed by interleaving 'ab' and 'cd' as a(s1)-c(s2)-b(s1)-d(s2), so the DP correctly finds a valid interleaving: true.

More Pseudocode and Code Tracing questions

Exams that ask this topic