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 = "babbbbb"
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. 19 7
  2. B. 18 7
  3. C. 17 7
  4. D. 12 5

Correct answer: B. 18 7

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

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

Exams that ask this topic