Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count palindromic substrings (each occurrence counts separately).

Problem: Count palindromic substrings (each occurrence counts separately).
def count_pal(s):
    n, c = len(s), 0
    for center in range(2 * n - 1):
        l, r = center // 2, center // 2 + center % 2
        while l >= 0 and r < n and s[l] == s[r]:
            c += 1; l -= 1; r += 1
    return c
print(count_pal("abc"), count_pal("aaa"), count_pal("abba"))
What is printed?
  1. A. 3 6 6
  2. B. 3 3 6
  3. C. 3 6 4
  4. D. 1 6 6

Correct answer: A. 3 6 6

There are 2n − 1 centres (letters and gaps); expand while the ends match and count each step. "aaa": a, a, a, aa, aa, aaa = 6. "abba": 4 letters + bb + abba = 6. Counting distinct palindromes instead would give 3 for "aaa". O(n²).

More Coding Interview Problems questions

Exams that ask this topic