Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count DISTINCT palindromic substrings by expanding around centres and collecting them in a set.

Problem: Count DISTINCT palindromic substrings by expanding around centres and collecting them in a set.
def distinct_pal(s):
    seen = 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]:
            seen.add(s[l:r+1]); l -= 1; r += 1
    return len(seen)
print(distinct_pal("abaaa"))
What is printed?
  1. A. 9
  2. B. 5
  3. C. 7
  4. D. 4

Correct answer: B. 5

Palindromes by position: a (×4), b, aba, aa (×2), aaa: 9 occurrences. Distinct strings: a, b, aba, aa, aaa = 5. Counting positions instead of distinct strings is the usual mix-up.

More Coding Interview Problems questions

Exams that ask this topic