ProgrammingHardProduct company OA

How many palindromic substrings does this code count?

How many palindromic substrings does this code count?
const char *s = "abba";
int n = 4, c = 0;
for (int i = 0; i < n; i++)
    for (int j = i; j < n; j++) {
        int a = i, b = j;
        while (a < b && s[a] == s[b]) { a++; b--; }
        if (a >= b) c++;
    }
printf("%d", c);
  1. A. 6
  2. B. 5
  3. C. 10
  4. D. 4

Correct answer: A. 6

Every substring s[i..j] is tested by moving inward while the ends match. The palindromes are the four single letters, "bb" and "abba": 6. '10' counts all substrings; '5' forgets "abba" or "bb".

More C Programming questions

Exams that ask this topic