Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every centre.

Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every centre.
def count(s):
    res = 0
    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]:
            res += 1; l -= 1; r += 1
    return res
print(count("aaab"))
What is printed?
  1. A. 4
  2. B. 7
  3. C. 5
  4. D. 10

Correct answer: B. 7

Single letters give 4; 'aa' occurs twice (positions 0–1 and 1–2); 'aaa' once: 4 + 2 + 1 = 7. Counting DISTINCT palindromes would give only 4 (a, b, aa, aaa).

More Coding Interview Problems questions

Exams that ask this topic