Data Structures & AlgorithmsModerateTCS NQT · string counting

Problem: How many palindromic substrings of length at least 1 does 'abcba' contain? Run the code.

Problem: How many palindromic substrings of length at least 1 does 'abcba' contain? Run the code.
s = 'abcba'
print(sum(1 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. 5
  2. B. 12
  3. C. 2
  4. D. 7

Correct answer: D. 7

The 5 single letters, 'bcb' and 'abcba' give 7 palindromic substrings. Stopping j at len(s) misses the substrings ending at the last character (5), starting j at i also counts 5 empty slices (12), and skipping single letters gives 2.

More Coding Interview Problems questions

Exams that ask this topic