Total Palindrome Substrings in a String
StringsAuto-graded · 22 test casesLast 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) <= 1000scontains 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation: counting via centers
Every palindromic substring has exactly one center. For odd-length palindromes the center is a single character; for even-length ones it is the gap between two adjacent characters. A string of length n therefore has 2n − 1 candidate centers.
For a given center, if the maximal palindrome you can form has radius k (meaning it stretches k characters in each direction, or k character pairs for even centers), then every smaller palindrome around that same center is also valid. So a center with maximal radius k contributes exactly k to the total count.
This means we never need to enumerate substrings explicitly — we just sum the maximal radius at every center.
Simple O(n²) version
The straightforward approach iterates over all 2n − 1 centers, expands outward while the flanking characters match, and accumulates the count. This runs in O(n²) time and O(1) extra space, and is entirely sufficient for n ≤ 1000.
Manacher's algorithm: O(n)
The reference solution applies Manacher's algorithm separately for odd and even centers.
Both passes maintain a window [left, right] — the palindrome found so far that extends furthest to the right.
When processing center i:
- If
ilies inside[left, right], its mirror position across the window's own center has already been computed. We reuse that radius as a lower bound, capped atright − i + 1to avoid assuming anything outside the known window. - We then try to expand further with a direct character comparison loop.
- If the new palindrome pushes past
right, we update[left, right].
The even pass is identical in structure, but the mirror index gets a +1 offset because even centers are indexed by their right-hand character rather than a shared midpoint.
Why it is correct
Each palindromic substring has exactly one center and one radius, so it is counted exactly once — by the pass and center it belongs to. Two identical substrings at different positions have different centers and are therefore counted separately, as required.
The mirror lower bound is valid because, inside [left, right], the text is symmetric around the window's center — any palindrome around the mirror that stays strictly inside the window must also appear around i. The cap ensures we make no claims beyond the boundary. The expansion loop then verifies everything beyond it directly, so the final radius is always exact.
Why the time complexity is O(n)
Each successful character comparison in the expansion loop advances right by one. Since right only increases and is bounded by n, the total number of successful comparisons across the entire pass is O(n). Each failed comparison terminates a center's expansion, happening at most once per center, so that is O(n) as well. Two passes gives O(n) overall.
Space is O(n) for the odd and even arrays.
Edge cases
| Input | Expected | Why |
|---|---|---|
"a" (single char) | 1 | odd[0] = 1, even[0] = 0 |
"aaa" (all same) | 6 | odd sums to 4, even sums to 2; general formula n(n+1)/2 |
"abc" (all distinct) | 3 | every radius is 1 for odd, 0 for even |
Reference solution
def count_palindrome_substrings(s: str) -> int:
n = len(s)
if n == 0:
return 0
total = 0
# --- Odd-length palindromes ---
# odd[i] = number of odd-length palindromes centered at index i
odd = [0] * n
left = 0
right = -1
for i in range(n):
radius = 1 if i > right else min(odd[left + right - i], right - i + 1)
while i - radius >= 0 and i + radius < n and s[i - radius] == s[i + radius]:
radius += 1
odd[i] = radius
total += radius
if i + radius - 1 > right:
left = i - radius + 1
right = i + radius - 1
# --- Even-length palindromes ---
# even[i] = number of even-length palindromes centered between i-1 and i
even = [0] * n
left = 0
right = -1
for i in range(n):
radius = 0 if i > right else min(even[left + right - i + 1], right - i + 1)
while i - radius - 1 >= 0 and i + radius < n and s[i - radius - 1] == s[i + radius]:
radius += 1
even[i] = radius
total += radius
if i + radius - 1 > right:
left = i - radius
right = i + radius - 1
return total