KatInterview

Total Palindrome Substrings in a String

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringsstringsdynamic-programmingtwo-pointers

Last updated

Tests your ability to count every palindromic substring by expanding around centers or applying Manacher's linear-time algorithm.

Total Palindrome Substrings in a String

Given a string s, count how many contiguous substrings of s are palindromes.

A palindrome reads the same forwards and backwards. Two substrings that share the same characters but start or end at different positions are treated as distinct and each contributes to the count.

Input

  • s: a non-empty string of lowercase English letters.

Output

Return a single integer: the total number of palindromic substrings.

Constraints

  • 1 <= len(s) <= 1000
  • s contains only lowercase English letters ('a'–'z').

Notes

  • Every single character is a palindrome, so the answer is always at least len(s).
  • Two occurrences of the same letter at different positions are counted separately.

Examples

Example 1

Input: count_palindrome_substrings('abc')

Output: 3

Example 2

Input: count_palindrome_substrings('aaa')

Output: 6

Example 3

Input: count_palindrome_substrings('abba')

Output: 6

Example 4

Input: count_palindrome_substrings('racecar')

Output: 10

Hints

Hint 1

Every palindrome has a center. A string of length n has 2n − 1 possible centers: n for odd-length palindromes (centered on a character) and n − 1 for even-length ones (centered between two characters). Try iterating over all centers and expanding outward while the flanking characters match.

Hint 2

For a given center, if expanding outward gives a palindrome of maximal radius k, then every shorter palindrome around that same center is also valid — so that center contributes exactly k to the total count.

Hint 3

To get from O(n²) to O(n), notice that if center i falls inside a palindrome you have already found, its mirror position on the other side of that palindrome's center has a radius you already computed. You can reuse that value (capped so it does not exceed the known palindrome's boundary) as a starting radius, then keep expanding from there. This is the core insight behind Manacher's algorithm.