Data Structures & AlgorithmsModerateTCS NQT · string counting

Problem: How many distinct palindromic substrings does 'aaaa' have? Run the code.

Problem: How many distinct palindromic substrings does 'aaaa' have? Run the code.
s = 'aaaa'
print(len({s[i:j] for i in range(len(s)) for j in range(i + 1, len(s) + 1) if s[i:j] == s[i:j][::-1]}))
What is printed?
  1. A. 10
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

The distinct palindromes are a, aa, aaa and aaaa. Counting all 10 positional substrings ignores that they repeat.

More Coding Interview Problems questions

Exams that ask this topic