ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (strings are indexed from 0)

What will be the output of the following pseudocode? (strings are indexed from 0)
String s = "AEBCBDA"
String t = reverse of s
Integer n = 7, L[0..7][0..7] = all 0
for (each i from 1 to n)
    for (each j from 1 to n)
        if (s[i - 1] == t[j - 1])
            L[i][j] = L[i - 1][j - 1] + 1
        else
            L[i][j] = max(L[i - 1][j], L[i][j - 1])
        end if
    end for
end for
Print L[n][n], n - L[n][n]
  1. A. 3 4
  2. B. 5 2
  3. C. 7 0
  4. D. 4 3

Correct answer: B. 5 2

The LCS of a string and its reverse is its longest palindromic subsequence, here ABCBA (length 5). The other 2 letters (E and D) must be deleted to leave a palindrome: 5 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic