Palindromic Substring Counter
StringsAuto-graded · 23 test casesLast updated
Tests ability to identify and count all palindromic substrings using center expansion and understanding of linear-time optimization techniques.
Write a function that takes a string containing only lowercase letters and returns the total number of substrings that read the same forwards and backwards.
Each substring is identified by its starting and ending positions. If the same sequence of characters appears multiple times at different positions, count each occurrence separately.
For instance, in "aaa", there are three single-character substrings ("a" at positions 0, 1, and 2), two two-character substrings ("aa" at positions 0-1 and 1-2), and one three-character substring ("aaa" at position 0-2), for a total of 6.
Constraints
- 0 ≤ length of string ≤ 1000
- String contains only lowercase ASCII letters (a-z)
- Empty string returns 0
Examples
Example 1
Input: count_palindromic_substrings('abc')
Output: 3
Example 2
Input: count_palindromic_substrings('aaa')
Output: 6
Example 3
Input: count_palindromic_substrings('ababa')
Output: 9
Hints
Hint 1
Consider that every palindrome expands symmetrically from a central point - either a single character or the gap between two characters.
Hint 2
For a string of length n, there are n potential single-character centers and n-1 potential between-character centers to check.
Hint 3
The quadratic approach expands outward from each center while characters match. A linear-time solution reuses information from previously computed centers through symmetry properties.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that palindromes expand symmetrically around a center point. Rather than checking every possible substring, we can identify all centers and expand outward from each one.
There are two types of centers to consider:
- Single-character centers for odd-length palindromes (like "aba")
- Between-character centers for even-length palindromes (like "abba")
For a string of length n, this gives us n + (n-1) = 2n-1 total centers to examine.
Quadratic Solution
From each center, expand outward while the characters on both sides match. Each successful expansion represents one palindromic substring, so increment the count with each step.
def count_palindromic_substrings(s: str) -> int:
n = len(s)
total = 0
def expand(left: int, right: int) -> int:
count = 0
while left >= 0 and right < n and s[left] == s[right]:
count += 1
left -= 1
right += 1
return count
for i in range(n):
total += expand(i, i) # odd-length palindromes
total += expand(i, i + 1) # even-length palindromes
return total
Time Complexity: O(n²) - There are O(n) centers, and each expansion can take up to O(n) steps in the worst case (such as "aaaa...").
Space Complexity: O(1) - Only using a few variables.
Linear-Time Optimization
Manacher's algorithm achieves O(n) time by exploiting symmetry. When processing a center that falls within a previously found palindrome, we can reuse information from the mirror position on the opposite side.
The algorithm maintains the rightmost palindrome boundary found so far. For any new center within this boundary, its initial radius can be derived from its mirror center's radius, bounded by the distance to the boundary. Only expansion beyond this known radius requires character comparisons.
Since the rightmost boundary only moves forward and is bounded by n, the total work across all centers is O(n).
The reference solution implements this optimization using two passes: one for odd-length palindromes and one for even-length palindromes. Each pass maintains:
- A radius array storing how far each palindrome extends
- The leftmost and rightmost bounds of the furthest-reaching palindrome
- For each position, compute the initial radius using symmetry, then expand
Time Complexity: O(n) - Each character is examined a constant number of times across all expansions.
Space Complexity: O(n) - Arrays to store radius information for each center.
Full Solution
def count_palindromic_substrings(s: str) -> int:
n = len(s)
total = 0
# Odd-length palindromes, centered on each character.
odd = [0] * n
left, right = 0, -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, right = i - radius + 1, i + radius - 1
# Even-length palindromes, centered between adjacent characters.
even = [0] * n
left, right = 0, -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, right = i - radius, i + radius - 1
return total