Palindrome Substrings Count
Last Updated :
04 Aug, 2025
Given a string s, find the total number of palindromic substrings of length greater than or equal to 2 present in the string.
A substring is palindromic if it reads the same forwards and backwards.
Examples:
Input: s = "abaab"
Output: 3
Explanation: Palindrome substrings (of length > 1) are "aba" , "aa" , "baab"
Input : s = "aaa"
Output: 3
Explanation : Palindrome substrings (of length > 1) are "aa" , "aa" , "aaa"
Input : s = "abbaeae"
Output: 4
Explanation : Palindrome substrings (of length > 1) are "bb" , "abba" , "aea", "eae"
Note: We have already discussed a naive and dynamic programming based solution in the article Count All Palindrome Sub-Strings in a String.
[Approach] Using Center Expansion - O(n^2) Time and O(1) Space
The idea is to consider each character of the given string as midpoint of a palindrome and expand it in both directions to find all palindromes of even and odd lengths.
- For odd length strings, there will be one center point
- For even length strings, there will be two center points.
- A character can be a center point of a odd length palindrome sub-string and/or even length palindrome sub-string.
C++
#include <iostream>
using namespace std;
int countPS(string& s) {
int n = s.size();
int count = 0;
// count odd length palndrome substrings
// with str[i] as center.
for (int i = 0; i < s.size(); i++) {
int left = i - 1;
int right = i + 1;
while (left >= 0 and right < n) {
if (s[left] == s[right])
count++;
else
break;
left--;
right++;
}
}
// count even length palindrome substrings
// where str[i] is first center.
for (int i = 0; i < s.size(); i++) {
int left = i;
int right = i + 1;
while (left >= 0 and right < n) {
if (s[left] == s[right])
count++;
else
break;
left--;
right++;
}
}
return count;
}
int main() {
string s = "abbaeae";
cout << countPS(s);
return 0;
}
Java
class GFG {
static int countPS(String s) {
int n = s.length();
int count = 0;
// count odd length palindrome substrings
// with str[i] as center.
for (int i = 0; i < s.length(); i++) {
int left = i - 1;
int right = i + 1;
while (left >= 0 && right < n) {
if (s.charAt(left) == s.charAt(right))
count++;
else
break;
left--;
right++;
}
}
// count even length palindrome substrings
// where str[i] is first center.
for (int i = 0; i < s.length(); i++) {
int left = i;
int right = i + 1;
while (left >= 0 && right < n) {
if (s.charAt(left) == s.charAt(right))
count++;
else
break;
left--;
right++;
}
}
return count;
}
public static void main(String[] args) {
String s = "abbaeae";
System.out.println(countPS(s));
}
}
Python
def countPS(s):
n = len(s)
count = 0
# count odd length palindrome substrings
# with str[i] as center.
for i in range(len(s)):
left = i - 1
right = i + 1
while left >= 0 and right < n:
if s[left] == s[right]:
count += 1
else:
break
left -= 1
right += 1
# count even length palindrome substrings
# where str[i] is first center.
for i in range(len(s)):
left = i
right = i + 1
while left >= 0 and right < n:
if s[left] == s[right]:
count += 1
else:
break
left -= 1
right += 1
return count
if __name__ == "__main__":
s = "abbaeae"
print(countPS(s))
C#
using System;
class GFG {
static int countPS(string s) {
int n = s.Length;
int count = 0;
// count odd length palindrome substrings
// with str[i] as center.
for (int i = 0; i < s.Length; i++) {
int left = i - 1;
int right = i + 1;
while (left >= 0 && right < n) {
if (s[left] == s[right])
count++;
else
break;
left--;
right++;
}
}
// count even length palindrome substrings
// where str[i] is first center.
for (int i = 0; i < s.Length; i++) {
int left = i;
int right = i + 1;
while (left >= 0 && right < n) {
if (s[left] == s[right])
count++;
else
break;
left--;
right++;
}
}
return count;
}
public static void Main() {
string s = "abbaeae";
Console.WriteLine(countPS(s));
}
}
JavaScript
function countPS(s) {
let n = s.length;
let count = 0;
// count odd length palindrome substrings
// with str[i] as center.
for (let i = 0; i < s.length; i++) {
let left = i - 1;
let right = i + 1;
while (left >= 0 && right < n) {
if (s[left] === s[right])
count++;
else
break;
left--;
right++;
}
}
// count even length palindrome substrings
// where str[i] is first center.
for (let i = 0; i < s.length; i++) {
let left = i;
let right = i + 1;
while (left >= 0 && right < n) {
if (s[left] === s[right])
count++;
else
break;
left--;
right++;
}
}
return count;
}
// Driver code
let s = "abbaeae";
console.log(countPS(s));
[Expected Approach] - Using Manacher's Algorithm
We use Manacher’s algorithm to find all palindromic substrings in linear time by computing the maximum radius of palindromes centered at each character (after modifying the string with separators). For each center, the number of palindromic substrings is proportional to half the radius. After summing over all centers, we subtract palindromic substrings of length 1 to count only those of length ≥ 2.
Step by Step Implementation:
- Preprocess the string: Insert a separator (#) between characters and add sentinels (@ at the beginning and $ at the end) to avoid bounds checking.
Example: "abba" → "@#a#b#b#a#$" - Initialize variables:
=> p[i] → stores the radius of the longest palindrome centered at position i
=> left, right → define the current longest palindrome boundaries in the modified string - Traverse the modified string: For each index i from left to right
=> Find the mirror position of i: mirror = left + (right - i)
=> If i is within the current palindrome window (i < right), initialize p[i] = min(p[mirror], right - i)
=> Try to expand the palindrome centered at i by comparing characters symmetrically on both sides
=> If the palindrome expands beyond right, update left = i - p[i] and right = i + p[i] - Count total palindromic substrings: For each p[i], number of palindromic substrings centered at i is ceil(p[i]/2). Add all such counts to get total palindromic substrings
- Exclude single length palindromes: The number of palindromic substrings of length 1 is equal to the length n of the original string. Subtract n to get the final count of substrings with length ≥ 2
C++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class manacher {
public:
// stores radius of palindromes centered
// at each position in ms
vector<int> p;
// modified string with sentinels and separators
string ms;
// constructor: builds modified string and
// runs manacher algorithm
manacher(string &s) {
ms = "@";
for (char c : s) {
ms += "#";
ms += c;
}
ms += "#$";
runManacher();
}
// core manacher's algorithm to compute radius array
void runManacher() {
int n = ms.size();
p.assign(n, 0);
int l = 0;
int r = 0;
for (int i = 1; i < n - 1; ++i) {
int mirror = r + l - i;
// assign minimum radius based on the
// mirror if within boundary
p[i] = max(0, min(r - i, p[mirror]));
// expand palindrome centered at i as
// far as possible
while (ms[i + 1 + p[i]] == ms[i - 1 - p[i]]) {
++p[i];
}
// update the current rightmost boundary
// if expanded past it
if (i + p[i] > r) {
l = i - p[i];
r = i + p[i];
}
}
}
// return the length of longest palindrome centered at
// cen in original string
int getLongest(int cen, int odd) {
int pos = 2 * cen + 2 + !odd;
return p[pos];
}
// check if substring s[l...r] is a palindrome
// using precomputed radius
bool check(int l, int r) {
int len = r - l + 1;
int center = (r + l) / 2;
int isOdd = len % 2;
return len <= getLongest(center, isOdd);
}
};
// function to count palindromic substrings of
// length >= 2
int countPS(string& s) {
manacher m(s);
int total = 0;
for (int i = 0; i < m.p.size(); ++i) {
// add ceil of (radius + 1) / 2 to count
// all palindromic substrings
total += (m.p[i] + 1) / 2;
}
// subtract the single-letter palindromes
// which are counted in the above
return total - s.length();
}
int main() {
string s = "abbaeae";
cout << countPS(s);
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
class Manacher {
// stores radius of palindromes centered
// at each position in ms
ArrayList<Integer> p;
// modified string with sentinels and separators
String ms;
// constructor: builds modified string and
// runs manacher algorithm
Manacher(String s) {
StringBuilder sb = new StringBuilder();
sb.append("@");
for (char c : s.toCharArray()) {
sb.append("#");
sb.append(c);
}
sb.append("#$");
ms = sb.toString();
runManacher();
}
// core manacher's algorithm to compute radius array
void runManacher() {
int n = ms.length();
p = new ArrayList<>(Collections.nCopies(n, 0));
int l = 0;
int r = 0;
for (int i = 1; i < n - 1; i++) {
int mirror = r + l - i;
// assign minimum radius based on the
// mirror if within boundary
if (i < r) {
p.set(i, Math.min(r - i, p.get(mirror)));
}
// expand palindrome centered at i as
// far as possible
while (ms.charAt(i + 1 + p.get(i)) == ms.charAt(i - 1 - p.get(i))) {
p.set(i, p.get(i) + 1);
}
// update the current rightmost boundary
// if expanded past it
if (i + p.get(i) > r) {
l = i - p.get(i);
r = i + p.get(i);
}
}
}
// return the length of longest palindrome centered at
// cen in original string
int getLongest(int cen, int odd) {
int pos = 2 * cen + 2 + (odd == 0 ? 1 : 0);
if (pos >= p.size()) {
return 0;
}
return p.get(pos);
}
// check if substring s[l...r] is a palindrome
// using precomputed radius
boolean check(int l, int r) {
int len = r - l + 1;
int center = (r + l) / 2;
int isOdd = len % 2;
return len <= getLongest(center, isOdd);
}
}
class GfG {
// function to count palindromic substrings of
// length >= 2
public static int countPS(String s) {
Manacher m = new Manacher(s);
int total = 0;
for (int i = 0; i < m.p.size(); i++) {
// add ceil of (radius + 1) / 2 to count
// all palindromic substrings
total += (m.p.get(i) + 1) / 2;
}
// subtract the single-letter palindromes
// which are counted in the above
return total - s.length();
}
public static void main(String[] args) {
String s = "abbaeae";
System.out.println(countPS(s));
}
}
Python
class Manacher:
def __init__(self, s):
# modified string with sentinels and separators
self.ms = "@"
for c in s:
self.ms += "#" + c
self.ms += "#$"
# stores radius of palindromes centered
# at each position in ms
self.p = [0] * len(self.ms)
# run the core algorithm
self.runManacher()
# core manacher's algorithm to compute radius array
def runManacher(self):
n = len(self.ms)
l, r = 0, 0
for i in range(1, n - 1):
mirror = r + l - i
# assign minimum radius based on mirror
self.p[i] = max(0, min(r - i, self.p[mirror]))
# expand palindrome centered at i
while self.ms[i + 1 + self.p[i]] == self.ms[i - 1 - self.p[i]]:
self.p[i] += 1
# update the current rightmost boundary
if i + self.p[i] > r:
l = i - self.p[i]
r = i + self.p[i]
# return the length of longest palindrome centered at
# cen in original string
def getLongest(self, cen, odd):
pos = 2 * cen + 2 + (0 if odd else 1)
return self.p[pos]
# check if substring s[l...r] is a palindrome
# using precomputed radius
def check(self, l, r):
length = r - l + 1
center = (r + l) // 2
isOdd = length % 2
return length <= self.getLongest(center, isOdd)
# function to count palindromic substrings of
# length >= 2
def countPS(s):
m = Manacher(s)
total = 0
for val in m.p:
# add ceil of (radius + 1) / 2 to count
total += (val + 1) // 2
# subtract the single-letter palindromes
return total - len(s)
if __name__ == "__main__":
s = "abbaeae"
print(countPS(s))
C#
using System;
using System.Collections.Generic;
class Manacher {
// stores radius of palindromes centered
// at each position in ms
public List<int> p;
// modified string with sentinels and separators
public string ms;
// constructor: builds modified string and
// runs manacher algorithm
public Manacher(string s) {
ms = "@";
foreach (char c in s) {
ms += "#";
ms += c;
}
ms += "#$";
runManacher();
}
// core manacher's algorithm to compute radius array
void runManacher() {
int n = ms.Length;
p = new List<int>(new int[n]);
int l = 0;
int r = 0;
for (int i = 1; i < n - 1; i++) {
int mirror = r + l - i;
// assign minimum radius based on the
// mirror if within boundary
if (i < r) {
p[i] = Math.Min(r - i, p[mirror]);
}
// expand palindrome centered at i as
// far as possible
while (ms[i + 1 + p[i]] == ms[i - 1 - p[i]]) {
p[i]++;
}
// update the current rightmost boundary
// if expanded past it
if (i + p[i] > r) {
l = i - p[i];
r = i + p[i];
}
}
}
// return the length of longest palindrome centered at
// cen in original string
public int getLongest(int cen, int odd) {
int pos = 2 * cen + 2 + (odd == 0 ? 1 : 0);
if (pos >= p.Count) {
return 0;
}
return p[pos];
}
// check if substring s[l...r] is a palindrome
// using precomputed radius
public bool check(int l, int r) {
int len = r - l + 1;
int center = (r + l) / 2;
int isOdd = len % 2;
return len <= getLongest(center, isOdd);
}
}
class GfG {
// function to count palindromic substrings of
// length >= 2
public static int countPS(string s) {
Manacher m = new Manacher(s);
int total = 0;
for (int i = 0; i < m.p.Count; i++) {
// add ceil of (radius + 1) / 2 to count
// all palindromic substrings
total += (m.p[i] + 1) / 2;
}
// subtract the single-letter palindromes
// which are counted in the above
return total - s.Length;
}
static void Main(string[] args) {
string s = "abbaeae";
Console.WriteLine(countPS(s));
}
}
JavaScript
class Manacher {
// builds modified string and runs manacher algorithm
constructor(s) {
this.ms = "@";
for (let c of s) {
this.ms += "#" + c;
}
this.ms += "#$";
// stores radius of palindromes
// centered at each position
this.p = new Array(this.ms.length).fill(0);
this.runManacher();
}
// core manacher's algorithm
// to compute radius array
runManacher() {
const n = this.ms.length;
let l = 0, r = 0;
for (let i = 1; i < n - 1; i++) {
let mirror = r + l - i;
if (i < r && mirror >= 0 && mirror < n) {
this.p[i] = Math.max(0, Math.min(r - i, this.p[mirror]));
}
while (this.ms[i + 1 + this.p[i]] === this.ms[i - 1 - this.p[i]]) {
this.p[i]++;
}
if (i + this.p[i] > r) {
l = i - this.p[i];
r = i + this.p[i];
}
}
}
// return the length of longest palindrome
// centered at cen in original string
getLongest(cen, odd) {
let pos = 2 * cen + 2 + (odd ? 0 : 1);
if (pos >= this.p.length) {
return 0;
}
return this.p[pos];
}
// check if substring s[l...r] is a palindrome
// using precomputed radius
check(l, r) {
let len = r - l + 1;
let center = Math.floor((r + l) / 2);
let isOdd = len % 2;
return len <= this.getLongest(center, isOdd);
}
}
// function to count palindromic
// substrings of length >= 2
function countPS(s) {
const m = new Manacher(s);
let total = 0;
for (let val of m.p) {
total += Math.floor((val + 1) / 2);
}
return total - s.length;
}
// Driver Code
let s = "abbaeae";
console.log(countPS(s));
Time Complexity: O(n)
Auxiliary Space: O(n), additional space is used for the modified string ms and the palindrome radius array p, both of size proportional to the original string length.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem