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")- A. false
- B. true
- C. Error: length mismatch
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode (counting pairs (i,j) with i<=j<=n whose product is divisible by n)? Integer n = 12, c…
- What will be the output of the following pseudocode (checking whether all characters in a string are unique)? Function…
- What will be the output of the following pseudocode (Hamming distance: number of differing bits between two integers)? (^ is bitwise XOR…
- What will be the output of the following pseudocode (finding the minimum in a rotated sorted array via binary search)? (Arrays are indexed…
- What will be the output of the following pseudocode (moving all zeros to the end while preserving the relative order of non-zero elements…
- What will be the output of the following pseudocode (length of the longest substring without repeating characters, sliding window)?…