Data Structures & AlgorithmsHardICPC regional · String round

Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too).

Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too).
def count(s):
    total = 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]:
            total += 1
            l -= 1
            r += 1
    return total
print(count('abacaba'))
What is printed?
  1. A. 7
  2. B. 12
  3. C. 9
  4. D. 5

Correct answer: B. 12

Expanding around all 2n − 1 centres counts 7 single letters, the three triples aba, aca, aba, the 5-letter bacab and the whole string: 12 occurrences. Counting distinct palindromic strings gives 7, a loop guard l > 0 instead of l >= 0 never reaches index 0 and gives 9, and skipping single letters gives 5.

More Coding Interview Problems questions

Exams that ask this topic