ProgrammingModerateCAT · MBA placement

Count the palindromic substrings (substrings of length 1 or more that read the same forwards and backwards, counted by position) of the string "aaa". The procedure below counts them by checking every substring. What is printed?

Count the palindromic substrings (substrings of length 1 or more that read the same forwards and backwards, counted by position) of the string "aaa". The procedure below counts them by checking every substring. What is printed?
count = 0
for i = 0 to n - 1
    for j = i to n - 1
        if s[i..j] is a palindrome then count = count + 1
    end for
end for
Print count
  1. A. 3
  2. B. 2
  3. C. 8
  4. D. 6

Correct answer: D. 6

All six substrings are palindromes: three single letters, two copies of aa and the whole word aaa. Counting only single letters gives 3, counting only length-2 substrings gives 2, and the number of subsets 2^3 = 8 is a different count.

More Pseudocode and Code Tracing questions

Exams that ask this topic