Data Structures & AlgorithmsVery hardGATE CS · DSA

Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?

Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?
s = "bbababa"
cnt, seen = 0, set()
for c in range(2 * len(s) - 1):
    l, r = c // 2, c // 2 + c % 2
    while l >= 0 and r < len(s) and s[l] == s[r]:
        cnt += 1; seen.add(s[l:r + 1]); l -= 1; r += 1
print(cnt, len(seen))
  1. A. 13 6
  2. B. 14 9
  3. C. 14 7
  4. D. 14 8

Correct answer: C. 14 7

Odd centres sit on characters and even centres between them; ignoring even centres misses palindromes like 'aa'. Output: 14 7.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic