ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; strings are indexed from 0)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division; strings are indexed from 0)
String s = "AAAB"
Integer c = 0, l, r
for (each center from 0 to 2 * length(s) - 2)
    l = center / 2
    r = l + center mod 2
    while (l >= 0 AND r < length(s) AND s[l] == s[r])
        c = c + 1
        l = l - 1
        r = r + 1
    end while
end for
Print c
  1. A. 4
  2. B. 10
  3. C. 6
  4. D. 7

Correct answer: D. 7

The 2n − 1 centres cover odd and even lengths, and every palindromic substring (counted by position) is found once. In AAAB: 4 single letters, AA twice, AAA once: 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic