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 = "BANANAS"
Integer best = 1, l, r, n = 7
for (each c from 0 to n - 1)
    l = c
    r = c
    while (l >= 0 AND r < n AND s[l] == s[r])
        if (r - l + 1 > best)
            best = r - l + 1
        end if
        l = l - 1
        r = r + 1
    end while
end for
Print best
  1. A. 5
  2. B. 3
  3. C. 7
  4. D. 4

Correct answer: A. 5

Expanding around each centre finds odd-length palindromes. Around the middle A (index 3) it grows A → NAN → ANANA, and then B ≠ S stops it. So best = 5.

More Pseudocode and Code Tracing questions

Exams that ask this topic