intermediate · strings · palindromes · expand around center · two pointers
Count the mirror-image substrings
Problem
Count the contiguous substrings of a word that read the same forwards and backwards. Substrings at different positions count separately even when their letters are equal.
Constraints
- 0 ≤ length ≤ 16 (visualization limit)
- letters a–z only
Examples
"aaa" → 6 — Three of length 1, two of length 2 ("aa" at 0 and at 1), one of length 3.
"abc" → 3
Show the solution
Expand around every center
Fix the middle of a palindrome. Its possible lengths form a chain: if the substring of radius r is a palindrome, so is the one of radius r − 1. So expanding until the first mismatch finds all palindromes with that middle.
Why it is correct
Each palindromic substring has exactly one center (one of the 2n − 1 letters or gaps), so it is counted from that center only. From a center, s[l..r] is a palindrome exactly when s[l] = s[r] and s[l+1..r−1] is a palindrome, so the expansion counts precisely the palindromes around that center and stops at the first radius that fails, after which every larger radius fails too.
Complexity
Time O(n²) worst case, extra space O(1). There are 2n − 1 centers and each expands at most n/2 times, so at most about n² comparisons; a word of one repeated letter reaches that bound. Most words stop after a step or two per center.
For contrast: Check every substring by comparing it with its reverse. That costs O(n³) time and O(n) space.
Edge cases
- Empty word: 0.
- One letter: 1.
- All letters equal: n(n + 1)/2.
- Even-length palindromes such as "abba" need the gap centers.
Common mistakes
- Expanding only from letters and missing even-length palindromes.
- Counting distinct palindromic strings instead of positions.
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class PalindromicSubstrings
{
/// <summary>Number of palindromic substrings (by position). Expand around each of the 2n - 1 centers: O(n^2) time, O(1) space.</summary>
public static int Count(string text)
{
int n = text.Length, total = 0;
for (int center = 0; center < 2 * n - 1; center++)
{
int left = center / 2;
int right = left + center % 2; // a letter (odd length) or the gap after it (even length)
while (left >= 0 && right < n && text[left] == text[right])
{
total++;
left--;
right++;
}
}
return total;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/PalindromicSubstrings.cs
def count(text: str) -> int:
"""Number of palindromic substrings (by position). Expand around each of the 2n - 1 centers: O(n^2)."""
n = len(text)
total = 0
for center in range(2 * n - 1):
left = center // 2
right = left + center % 2 # a letter (odd length) or the gap after it (even length)
while left >= 0 and right < n and text[left] == text[right]:
total += 1
left -= 1
right += 1
return total
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/palindromic_substrings.py
package dev.bekadan.dsa.problems;
public final class PalindromicSubstrings {
private PalindromicSubstrings() {
}
/** Number of palindromic substrings (by position). Expand around each of the 2n - 1 centers: O(n^2). */
public static int count(String text) {
int n = text.length();
int total = 0;
for (int center = 0; center < 2 * n - 1; center++) {
int left = center / 2;
int right = left + center % 2; // a letter (odd length) or the gap after it (even length)
while (left >= 0 && right < n && text.charAt(left) == text.charAt(right)) {
total++;
left--;
right++;
}
}
return total;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/PalindromicSubstrings.java
#pragma once
#include <string_view>
namespace bekadan::dsa::problems {
// Number of palindromic substrings (by position). Expand around each of the 2n - 1 centers: O(n^2).
inline int palindromic_substrings(std::string_view text) {
const int n = static_cast<int>(text.size());
int total = 0;
for (int center = 0; center < 2 * n - 1; ++center) {
int left = center / 2;
int right = left + center % 2; // a letter (odd length) or the gap after it (even length)
while (left >= 0 && right < n && text[static_cast<std::size_t>(left)] == text[static_cast<std::size_t>(right)]) {
++total;
--left;
++right;
}
}
return total;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/palindromic_substrings.hpp