The Wayback Machine - https://web.archive.org/web/20240917185243/https://www.geeksforgeeks.org/count-palindrome-sub-strings-string/
Open In App

Palindrome Substrings Count

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string, the task is to count all palindrome sub string in a given string. Length of palindrome sub string is greater than or equal to 2. 

Examples:

Input : s = “abaab”
Output: 3
Explanation : Palindrome substrings (of length > 1) are “aba” , “aa” , “baab”

Input : s = “aaa”
Output: 3
Explanation : Palindrome substring (of length > 1) are “aa” , “aa” , “aaa”

Input : s = “abbaeae”
Output: 4
Explanation : Palindrome substring (of length > 1) are “bb” , “abba” , “aea”, “eae”

Naive Solution – O(n^3) Time

  1. Consider all possible substrings from index i to j by running nested loops.
  2. For every substring from i to j, check if it is palindrome.
C++
#include<bits/stdc++.h>
using namespace std;

// Function to check if the substring from i to j is a palindrome
bool isPal(string& s, int i, int j) {
    while (i < j) {
        if (s[i] != s[j]) return false;
        i++;
        j--;
    }
    return true;
}

// Counts palindromic substrings of length more than 2
int countPS(string& s) {
    int n = s.length();  
   
    // Consider all possible substrings of lengths
    // more than 1
    int res = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i+1; j < n; j++) {
            if (isPal(s, i, j)) { // Is Palindrome
                res++;  
            }
        }
    }

    return res;
}

// Driver code
int main() {
    string s = "aaa";
    cout << countPS(s);
    return 0;
}
Java
public class GfG {

    // Function to check if the substring from i to j
    // is a palindrome
    public static boolean isPal(String s, int i, int j) {
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    // Counts palindromic substrings of length more than 2
    public static int countPS(String s) {
        int n = s.length();
        int res = 0;

        // Consider all possible substrings of 
        // length greater than 1
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (isPal(s, i, j)) {
                    res++;
                }
            }
        }

        return res;
    }

    // Driver code
    public static void main(String[] args) {
        String s = "aaa";
        System.out.println(countPS(s)); // Output: 3
    }
}
Python
# Function to check if the substring from i to j 
# is a palindrome
def isPal(s, i, j):
    while i < j:
        if s[i] != s[j]:
            return False
        i += 1
        j -= 1
    return True

# Counts palindromic substrings of length more than 2
def countPS(s):
    n = len(s)
    res = 0

    # Consider all possible substrings of length 
    # greater than 1
    for i in range(n):
        for j in range(i + 1, n):
            if isPal(s, i, j):
                res += 1

    return res

# Driver code
if __name__ == "__main__":
    s = "aaa"
    print(countPS(s))  # Output: 3

Output
3

Memoization – O(n^2) Time

If we take a closer look, we can notice that we are checking same substrings for palindrome again and again. Imagine a recursive isPal(i, j) function that calls for isPal(i + i, j-1) if the last two characters match.

bool isPal(s, i, j) {

// Base case: if i crosses j or
// they’re the same, it’s a palindrome
if (i >= j) return true;

// Check if the characters at i and j are equal and
// recursively check for the substring in between
return (s[i] == s[j]) && isPal(s, i + 1, j – 1);
}

We can avoid recomputing overlapping Subproblems by making a 2D array memo.

  1. Size of the memo is going to be n x n as both staring and ending indexes range from 0 to n-1
  2. memo[i][j] = true if substring from i to j is palindrome, and false otherwise
  3. Before checking any substring for palindrom, we do a lookup in the memo table.
C++
#include<bits/stdc++.h>
using namespace std;

// Function to use memoization to check if a 
// substring is palindrome
bool isPal(int i, int j, string& s, vector<vector<int>>& memo) {
    if (i >= j) return true; 
    
    // If current substring is already checked
    if (memo[i][j] != -1) return memo[i][j]; 

    // Check if the characters at i and j are equal and the 
    // substring inside is palindrome
    memo[i][j] = (s[i] == s[j] && isPal(i + 1, j - 1, s, memo));
  
    return memo[i][j];
}

// Counts palindromic substrings of length more than 1
int countPS(string& s) {
    int n = s.length();
  
    // Memoization table
    vector<vector<int>> memo(n, vector<int>(n, -1));

    int res = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
          
             // Check if the substring is palindrome
            if (isPal(i, j, s, memo)) { 
                res++;
            }
        }
    }

    return res;
}

// Driver code
int main() {
    string s = "aaa";
    cout << countPS(s);
    return 0;
}
Java
import java.util.Arrays;

public class PalindromeSubstringsMemo {

    // Function to use memoization to check if a substring 
    // is palindrome
    public static boolean isPal(int i, int j, String s,
                                int[][] memo) {
         
         // Base case: single character or empty substring
        if (i >= j) return true;

        // If current substring is already checked
        if (memo[i][j] != -1) return memo[i][j] == 1;

        // Check if characters at i and j are equal 
        // and substring inside is palindrome
        memo[i][j] = (s.charAt(i) == s.charAt(j) && 
                      isPal(i + 1, j - 1, s, memo)) ? 1 : 0;
        return memo[i][j] == 1;
    }

    // Function to count palindromic substrings of length more than 1
    public static int countPS(String s) {
        int n = s.length();

        // Memoization table
        int[][] memo = new int[n][n];
        for (int[] row : memo) {
            Arrays.fill(row, -1); // Initialize the memo table to -1
        }

        int res = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
              
                // Check if the substring is palindrome
                if (isPal(i, j, s, memo)) {
                    res++;
                }
            }
        }

        return res;
    }

    // Driver code
    public static void main(String[] args) {
        String s = "aaa";
        System.out.println(countPS(s)); // Output: 3
    }
}
Python
def isPal(i, j, s, memo):
  
     # Base case: single character or empty substring
    if i >= j:
        return True 

    # If current substring is already checked
    if memo[i][j] != -1:
        return memo[i][j] == 1

    # Check if the characters at i and j are equal 
    # and substring inside is palindrome
    memo[i][j] = 1 if (s[i] == s[j] and 
                       isPal(i + 1, j - 1, s, memo)) else 0
    
    return memo[i][j] == 1

# Function to count palindromic substrings 
# of length more than 1
def countPS(s: str) -> int:
    n = len(s)

    # Memoization table
    memo = [[-1] * n for _ in range(n)]

    res = 0
    for i in range(n):
        for j in range(i + 1, n):
          
            # Check if the substring is palindrome
            if isPal(i, j, s, memo):
                res += 1

    return res

# Driver code
if __name__ == "__main__":
    s = "aaa"
    print(countPS(s))  # Output: 3

Output
3

Time Complexity: O(n3) 
Auxiliary Space: O(n2) 

Bottom-Up DP – O(n^2) Time

We create a dp array of size n x n. The main point to note here is, we cannot simply fill the dp table from i = 0 to n-1 and then j from i to n – 1. To fill an entry (i, j), we would need value of (i+1, j-1). Like Matrix Chain Multiplication, we need to fill values in diagonal manner using gap variable.

  1. We first fill the main diagnoal or gap = 0 (or i = j) as we know a single character string is palindrome.
  2. Then we fill for gap = 1 (or j = i+1). If s[i] and s[j] are same, then answer is true, else false
  3. Then we fill remaining entries using results of dp[i+1][j-1]
C++
#include <bits/stdc++.h>
using namespace std;

// Returns total number of palindrome substrings of 
// length greater than or equal to 2
int countPS(string& s) {
    int n = s.length();
    int res = 0;

    // dp[i][j] = true if substring s[i..j] is a palindrome
    vector<vector<bool>> dp(n, vector<bool>(n, false));

    // Palindromes of single length, gap = 0
    for (int i = 0; i < n; i++) {
        dp[i][i] = true;
    }

    // Explicitly handle the case where gap = 1 (substrings of length 2)
    for (int i = 0; i < n - 1; i++) {
        if (s[i] == s[i + 1]) {
            dp[i][i + 1] = true;
            res++;
        }
    }

    // Handle palindromes of length greater than 2 (gap >= 2)
    for (int gap = 2; gap <= n; gap++) {
        for (int i = 0; i <= n - gap; i++) {
            int j = i + gap;

            // Check if the current string is a palindrome
            if (s[i] == s[j] && dp[i + 1][j - 1]) {
                dp[i][j] = true;
                res++;
            }
        }
    }
  
    return res;
}

// Driver code
int main() {
    string s = "aaa";
    cout << countPS(s) << endl;
    return 0;
}
Java
import java.util.Arrays;

public class GfG {

    // Returns total number of palindrome 
    // substrings of length greater than or equal to 2
    public static int countPS(String s) {
        int n = s.length();
        int res = 0;

        // dp[i][j] = true if substring s[i..j] is a palindrome
        boolean[][] dp = new boolean[n][n];

        // Palindromes of single length, gap = 0
        for (int i = 0; i < n; i++) {
            dp[i][i] = true;
        }

        // Explicitly handle the case where gap = 1 
        // (substrings of length 2)
        for (int i = 0; i < n - 1; i++) {
            if (s.charAt(i) == s.charAt(i + 1)) {
                dp[i][i + 1] = true;
                res++;
            }
        }

        // Handle palindromes of length greater than 2 (gap >= 2)
        for (int gap = 2; gap < n; gap++) {
            for (int i = 0; i <= n - gap - 1; i++) {
                int j = i + gap;

                // Check if the current string is a palindrome
                if (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]) {
                    dp[i][j] = true;
                    res++;
                }
            }
        }

        return res;
    }

    // Driver code
    public static void main(String[] args) {
        String s = "aaa";
        System.out.println(countPS(s));
    }
}
Python
def countPS(s: str) -> int:
    n = len(s)
    res = 0

    # dp[i][j] = True if substring s[i..j] is a palindrome
    dp = [[False] * n for _ in range(n)]

    # Palindromes of single length, gap = 0
    for i in range(n):
        dp[i][i] = True

    # Explicitly handle the case where gap = 1 
    # (substrings of length 2)
    for i in range(n - 1):
        if s[i] == s[i + 1]:
            dp[i][i + 1] = True
            res += 1

    # Handle palindromes of length greater than 2 (gap >= 2)
    for gap in range(2, n):
        for i in range(n - gap):
            j = i + gap

            # Check if the current string is a palindrome
            if s[i] == s[j] and dp[i + 1][j - 1]:
                dp[i][j] = True
                res += 1

    return res

# Driver code
if __name__ == "__main__":
    s = "aaa"
    print(countPS(s))

Output
3

Time Complexity: O(n2) 
Auxiliary Space: O(n2) 

Using Center Expansion:

We can further optimize using the idea of center expansion. We have used this idea in Longest Palindromic Substring also. With this basic idea we can solve this problem in O(n^2) time and O(1) Space. We can further enhance it to work in linear time. Please refer Count All Palindrome Sub-Strings using Center Expansion for details

Find all distinct palindromic sub-strings of a given string




Previous Article
Next Article

Similar Reads

Count pair of strings whose concatenation of substrings form a palindrome
Given an array of strings arr[], the task is to count the pair of strings whose concatenation of substrings form a palindrome.Examples: Input: arr[] = {"gfg", "gfg"} Output: 1 Explanation: One possible way of choosing s1 and s2 is s1 = "gf", s2 = "g" such that s1 + s2 i.e "gfg" is a palindrome.Input: arr[] = {"abc", B = "def"} Output: 0 Approach: T
5 min read
Count substrings of a given string whose anagram is a palindrome
Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Since all substrings are have palindromic anagrams, th
10 min read
Palindrome Substrings Count using Center Expansion
Given a string, the task is to count all palindrome sub string in a given string. Length of palindrome sub string is greater than or equal to 2. Examples: Input : s = "abaab"Output: 3Explanation : Palindrome substrings (of length &gt; 1) are "aba" , "aa" , "baab" Input : s = "aaa"Output: 3Explanation : Palindrome substring (of length &gt; 1) are "a
5 min read
Count all palindrome which is square of a palindrome
Given two positive integers L and R (represented as strings) where [Tex]1\leq L \leq R\leq10^{18} [/Tex]. The task is to find the total number of super-palindromes in the inclusive range [L, R]. A palindrome is called super-palindrome if it is a palindrome and also square of a palindrome. Examples: Input: L = "4", R = "1000" Output: 4 Explanation:
10 min read
Check if concatenation of splitted substrings of two given strings forms a palindrome or not
Given two strings a and b of the same length, the task is to check if splitting both the strings and concatenating their opposite substrings, i.e. concatenating the left substring of a with right substring of b or concatenating the left substring of b with right substring of a, forms a palindrome or not. If found to be true print "Yes". Otherwise,
8 min read
Check if substrings from three given strings can be concatenated to form a palindrome
https://write.geeksforgeeks.org/internshipGiven three strings S1, S2, and S3 of lengths L, M, and N respectively, the task is to check if it is possible to choose some non-empty substrings from S1, S2, and S3 such that their concatenation is a palindrome. If found to be true, print "YES". Otherwise, print "NO". Examples: Input: S1 = "adcb", S2 = "b
5 min read
Minimum moves to make String Palindrome incrementing all characters of Substrings
Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following operations:Select the substring "4341". The string
6 min read
Minimum steps to delete a string after repeated deletion of palindrome substrings
Given a string containing characters as integers only. We need to delete all characters of this string in a minimum number of steps wherein in one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated. Examples: Input : s = “2553432” Output : 2 We can delete all character of above string
15+ min read
Sentence Palindrome (Palindrome after removing spaces, dots, .. etc)
Write a program to check if a sentence is a palindrome or not. You can ignore white spaces and other characters to consider sentences as a palindrome. Examples: Input : str = "Too hot to hoot." Output : Sentence is palindrome. Input : str = "Abc def ghi jklm." Output : Sentence is not palindrome. Note: There may be multiple spaces and/or dots betwe
12 min read
Count ways to split a Binary String into three substrings having equal count of zeros
Given binary string str, the task is to count the total number of ways to split the given string into three non-overlapping substrings having the same number of 0s. Examples: Input: str = "01010" Output: 4 Explanation: The possible splits are: [0, 10, 10], [01, 01, 0], [01, 0, 10], [0, 101, 0] Input: str = "11111" Output: 0 Approach: To solve the p
15+ min read
Count the sum of count of distinct characters present in all Substrings
Given a string S consisting of lowercase English letters of size N where (1 &lt;= N &lt;= 105), the task is to print the sum of the count of distinct characters N where (1 &lt;= N &lt;= 105)in all the substrings. Examples: Input: str = "abbca"Output: 28Explanation: The following are the substrings of "abbca":=&gt; Sum of distinct characters in Subs
8 min read
Count of binary strings of length N having equal count of 0's and 1's and count of 1's &ge; count of 0's in each prefix substring
Given an integer N, the task is to find the number of possible binary strings of length N with an equal frequency of 0's and 1's in which frequency of 1's are greater or equal to the frequency of 0's in every prefix substring. Examples: Input: N = 2Output: 1Explanation:All possible binary strings of length 2 are {"00", "01", "10" and "11"}. Out of
7 min read
Count substrings with each character occurring at most k times
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets. Examples: Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2 Output : 12 Substrings that have individual chara
15+ min read
Permutation of given string that maximizes count of Palindromic substrings
Given a string S, the task is to find the permutation of the string such that palindromic substrings in the string are maximum.Note: There can be multiple answers for each string. Examples: Input: S = "abcb" Output: "abbc" Explanation: "abbc" is the string with maximum number of palindromic substrings. Palindromic Substrings are - {"a", "b", "b", "
3 min read
Count substrings that starts with character X and ends with character Y
Given a string str of n lowercase characters, the task is to count the number of substrings of str starting with character X and ending with character Y. Examples: Input: str = "abbcaceghcak" x = 'a', y = 'c' Output: 5 abbc, abbcac, ac, abbcaceghc, aceghc Input: str = "geeksforgeeks" x = 'g', y = 'e' Output: 6 Approach: Initialize two counters i.e.
6 min read
Count number of substrings with numeric value greater than X
Given a string 'S' (composed of digits) and an integer 'X", the task is to count all the sub-strings of 'S' that satisfy the following conditions: The sub-string must not begin with the digit '0'.And the numeric number it represents must be greater than 'X'. Note: Two ways of selecting a sub-string are different if they begin or end at different in
5 min read
Count the number of vowels occurring in all the substrings of given string
Given a string of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = "abc" Output: 3The given string "abc" contains only one vowel = 'a' Substrings of "abc" are = {"a", "b", "c", "ab", "bc, "abc"} Hence, the sum of occu
12 min read
Find the count of substrings in alphabetic order
Given a string of length [Tex]N [/Tex]consisting of lowercase alphabets. The task is to find the number of such substrings whose characters occur in alphabetical order. Minimum allowed length of substring is 2. Examples: Input : str = "refjhlmnbv" Output : 2 Substrings are: "ef", "mn" Input : str = "qwertyuiopasdfghjklzxcvbnm" Output : 3 For a subs
4 min read
Count number of distinct substrings of a given length
Given a string S of length N consisting of lower-case English alphabets and an integer 'l', find the number of distinct substrings of length 'l' of the given string. Examples: Input : s = "abcbab", l = 2 Output : 4 All distinct sub-strings of length 2 will be {"ab", "bc", "cb", "ba"} Thus, answer equals 4. Input : s = "ababa", l = 2 Output : 2 Naiv
6 min read
Count of substrings which contains a given character K times
Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contains 2 exactly 1 time. Input : str = "55555", c = '5'
9 min read
Count number of substrings of a string consisting of same characters
Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.Let's initialize the result to 0. Travers
6 min read
Count all substrings having character K
Given a string str and a character K, the task is to find the count of all the substrings of str that contain the character K.Examples: Input: str = "geeks", K = 'g' Output: 5 "g", "ge", "gee", "geek" and "geeks" are the valid substrings.Input: str = "geeksforgeeks", K = 'k' Output: 56 Naive approach A simple approach will be to find all the substr
7 min read
Queries to find the count of vowels in the substrings of the given string
Given string str of length N and Q queries where every query consists of two integers L and R. For every query, the task is to find the count of vowels in the substring str[L...R]. Examples: Input: str = "geeksforgeeks", q[][] = {{1, 3}, {2, 4}, {1, 9}} Output: 2 1 4 Query 1: "eek" has 2 vowels. Query 2: "eks" has 1 vowel. Query 3: "eeksforge" has
12 min read
Count of Substrings that can be formed without using the given list of Characters
Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given string, substring "cd" is left. Therefore, the tota
7 min read
Count of substrings whose Decimal equivalent is greater than or equal to K
Given an integer K and a binary string S of length N, the task is to find out the number of substrings whose decimal equivalent is greater than or equal to K. Examples: Input: K = 3, S = "11100" Output: 8 Explanation: There are 8 such substring whose decimal equivalent is greater than or equal to 3, as mentioned below: Substring - Decimal Equivalen
12 min read
Count of all unique substrings with non-repeating characters
Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 Approach: The idea is to iterate over all the substri
6 min read
Count the number of vowels occurring in all the substrings of given string | Set 2
Given a string str[] of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = “abc” Output: 3The given string “abc” contains only one vowel = ‘a’ Substrings of “abc” are = {“a”, “b”, “c”, “ab”, “bc, “abc”} Hence, the sum o
5 min read
Count of substrings consisting only of vowels
Given a string S, the task is to count all substrings which contain only vowels. Examples: Input: S = "geeksforgeeks" Output: 7 Explanation: Substrings {"e", "ee", "e", "o", "e", "ee", "e"} consists only of vowels. Input: S = "aecui" Output: 6 Explanation: Substrings {"a", "ae", "e", "u", "ui", "i"} consists only of vowels. Naive Approach: To simpl
11 min read
Count of substrings formed using a given set of characters only
Given a string str and an array arr[] of K characters, the task is to find the number of substrings of str that contain characters only from the given character array arr[]. Note: The string str and the arr[] contain only lowercase alphabets. Examples: Input: S = "abcb", K = 2, charArray[] = {'a', 'b'}Output: 4Explanation:The substrings are "a", "a
8 min read
Count Substrings with number of 0s and 1s in ratio of X : Y
Given a binary string S, the task is to count the substrings having the number of 0s and 1s in the ratio of X : Y Examples: Input: S = "010011010100", X = 3, Y = 2Output: 5Explanation: The index range for the 5 substrings are: (0, 4), (2, 6), (6, 10), (7, 11), (2, 11) Input: S = "10010101", X = 1, Y = 2Output: 2 Naive Approach: The Naive approach f
7 min read