Open In App

Palindrome Substrings Count

Last Updated : 04 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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));

Output
4

[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));

Output
4

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.


Article Tags :
Practice Tags :

Similar Reads