Data Structures & AlgorithmsVery hardProduct company OA

Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed?

Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed?
def pal(s):
    c = 0
    for center in range(2 * len(s) - 1):
        l = center // 2; r = l + center % 2
        while l >= 0 and r < len(s) and s[l] == s[r]: c += 1; l -= 1; r += 1
    return c
print(pal("aabaa"), pal("abcba"), pal("aaaa"))
  1. A. 9 5 10
  2. B. 7 7 10
  3. C. 9 7 6
  4. D. 9 7 10

Correct answer: D. 9 7 10

Each centre (a character or a gap) expands while the ends match, adding one palindrome per step. aabaa: 5 singles + 'aa' twice + 'aba' + 'aabaa' = 9. abcba: 5 + 'bcb' + 'abcba' = 7. aaaa: every substring is a palindrome, 4·5/2 = 10. Forgetting the even (gap) centres misses 'aa' and gives 7 for aabaa. O(n²) worst case; Manacher is O(n).

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

Exams that ask this topic