ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def cnt_pal(s):
    n = len(s)
    c = 0
    for ctr in range(2 * n - 1):
        l, r = ctr // 2, ctr // 2 + ctr % 2
        while l >= 0 and r < n and s[l] == s[r]:
            c += 1
            l -= 1
            r += 1
    return c
print(cnt_pal('aaa'), cnt_pal('abc'))
  1. A. 4 3
  2. B. 6 3
  3. C. 6 2
  4. D. 5 3

Correct answer: B. 6 3

Expanding around each of the 2n - 1 centres counts palindromes. 'aaa' has 3 single letters, 2 pairs and 1 triple, which is 6, and 'abc' has 3 single letters.

More Python Programming questions

Exams that ask this topic