Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Check if concatenation of splitted substrings of two given strings forms a palindrome or not
Next article icon

Count of ways to split given string into two non-empty palindromes

Last Updated : 25 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S, the task is to find the number of ways to split the given string S into two non-empty palindromic strings.
Examples:

Input: S = “aaaaa” 
Output: 4 
Explanation: 
Possible Splits: {“a”, “aaaa”}, {“aa”, “aaa”}, {“aaa”, “aa”}, {“aaaa”, “a”}
Input: S = “abacc” 
Output: 1 
Explanation: 
Only possible split is “aba”, “cc”.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The naive approach is to split the string at each possible index and check if both the substrings are palindromic or not. If yes then increment the count for that index. Print the final count.
Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to check whether the
// substring from l to r is
// palindrome or not
bool isPalindrome(int l, int r,
                  string& s)
{
 
    while (l <= r) {
 
        // If characters at l and
        // r differ
        if (s[l] != s[r])
 
            // Not a palindrome
            return false;
 
        l++;
        r--;
    }
 
    // If the string is
    // a palindrome
    return true;
}
 
// Function to count and return
// the number of possible splits
int numWays(string& s)
{
    int n = s.length();
 
    // Stores the count
    // of splits
    int ans = 0;
    for (int i = 0;
         i < n - 1; i++) {
 
        // Check if the two substrings
        // after the split are
        // palindromic or not
        if (isPalindrome(0, i, s)
            && isPalindrome(i + 1,
                            n - 1, s)) {
 
            // If both are palindromes
            ans++;
        }
    }
 
    // Print the final count
    return ans;
}
 
// Driver Code
int main()
{
    string S = "aaaaa";
 
    cout << numWays(S);
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
class GFG{
     
// Function to check whether the
// substring from l to r is
// palindrome or not
public static boolean isPalindrome(int l, int r,
                                   String s)
{
    while (l <= r)
    {
         
        // If characters at l and
        // r differ
        if (s.charAt(l) != s.charAt(r))
             
            // Not a palindrome
            return false;
             
        l++;
        r--;
    }
 
    // If the string is
    // a palindrome
    return true;
}
 
// Function to count and return
// the number of possible splits
public static int numWays(String s)
{
    int n = s.length();
 
    // Stores the count
    // of splits
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
        
       // Check if the two substrings
       // after the split are
       // palindromic or not
       if (isPalindrome(0, i, s) &&
           isPalindrome(i + 1, n - 1, s))
       {
            
           // If both are palindromes
           ans++;
       }
    }
     
    // Print the final count
    return ans;
}
 
// Driver Code
public static void main(String args[])
{
    String S = "aaaaa";
 
    System.out.println(numWays(S));
}
}
 
// This code is contributed by SoumikMondal
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to check whether the
# substring from l to r is
# palindrome or not
def isPalindrome(l, r, s):
 
    while (l <= r):
         
        # If characters at l and
        # r differ
        if (s[l] != s[r]):
             
            # Not a palindrome
            return bool(False)
             
        l += 1
        r -= 1
 
    # If the string is
    # a palindrome
    return bool(True)
 
# Function to count and return
# the number of possible splits
def numWays(s):
     
    n = len(s)
 
    # Stores the count
    # of splits
    ans = 0
    for i in range(n - 1):
         
        # Check if the two substrings
        # after the split are
        # palindromic or not
        if (isPalindrome(0, i, s) and
            isPalindrome(i + 1, n - 1, s)):
                 
            # If both are palindromes
            ans += 1
     
    # Print the final count
    return ans
 
# Driver Code
S = "aaaaa"
 
print(numWays(S))
 
# This code is contributed by divyeshrabadiya07
 
 

C#




// C# program to implement
// the above approach
using System;
class GFG{
      
// Function to check whether the
// substring from l to r is
// palindrome or not
public static bool isPalindrome(int l, int r,
                                string s)
{
    while (l <= r)
    {
          
        // If characters at l and
        // r differ
        if (s[l] != s[r])
              
            // Not a palindrome
            return false;
              
        l++;
        r--;
    }
  
    // If the string is
    // a palindrome
    return true;
}
  
// Function to count and return
// the number of possible splits
public static int numWays(string s)
{
    int n = s.Length;
  
    // Stores the count
    // of splits
    int ans = 0;
    for(int i = 0; i < n - 1; i++)
    {
         
       // Check if the two substrings
       // after the split are
       // palindromic or not
       if (isPalindrome(0, i, s) &&
           isPalindrome(i + 1, n - 1, s))
       {
             
           // If both are palindromes
           ans++;
       }
    }
      
    // Print the final count
    return ans;
}
  
// Driver Code
public static void Main(string []args)
{
    string S = "aaaaa";
  
    Console.Write(numWays(S));
}
}
 
// This code is contributed by Rutvik
 
 

Javascript




<script>
 
    // Javascript program to implement
    // the above approach 
       
    // Function to check whether the
    // substring from l to r is
    // palindrome or not
    function isPalindrome(l, r, s)
    {
        while (l <= r)
        {
 
            // If characters at l and
            // r differ
            if (s[l] != s[r])
 
                // Not a palindrome
                return false;
 
            l++;
            r--;
        }
 
        // If the string is
        // a palindrome
        return true;
    }
 
    // Function to count and return
    // the number of possible splits
    function numWays(s)
    {
        let n = s.length;
 
        // Stores the count
        // of splits
        let ans = 0;
        for(let i = 0; i < n - 1; i++)
        {
 
           // Check if the two substrings
           // after the split are
           // palindromic or not
           if (isPalindrome(0, i, s) && 
               isPalindrome(i + 1, n - 1, s))
           {
 
               // If both are palindromes
               ans++;
           }
        }
 
        // Print the final count
        return ans;
    }
     
    let S = "aaaaa";
    
    document.write(numWays(S));
 
</script>
 
 
Output
4   

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using the Hashing and Rabin-Karp Algorithm to store Prefix and Suffix Hashes of the string. Follow the steps below to solve the problem:

  • Compute prefix and suffix hash of the given string.
  • For every index i in the range [1, N – 1], check if the two substrings [0, i – 1] and [i, N – 1] are palindrome or not.
  • To check if a substring [l, r] is a palindrome or not, simply check:
PrefixHash[l - r] = SuffixHash[l - r]
  • For every index i for which two substrings are found to be palindromic, increase the count.
  • Print the final value of count.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
 
#include
using namespace std;
 
// Modulo for rolling hash
const int MOD = 1e9 + 9;
 
// Small prime for rolling hash
const int P = 37;
 
// Maximum length of string
const int MAXN = 1e5 + 5;
 
// Stores prefix hash
vector prefixHash(MAXN);
 
// Stores suffix hash
vector suffixHash(MAXN);
 
// Stores inverse modulo
// of P for prefix
vector inversePrefix(MAXN);
 
// Stores inverse modulo
// of P for suffix
vector inverseSuffix(MAXN);
 
int n;
int power(int x, int y, int mod)
{
    // Function to compute
    // power under modulo
    if (x == 0)
        return 0;
 
    int ans = 1;
    while (y > 0) {
        if (y & 1)
            ans = (1LL * ans * x)
                % MOD;
 
        x = (1LL * x * x) % MOD;
        y >>= 1;
    }
    return ans;
}
 
// Precompute hashes for the
// given string
void preCompute(string& s)
{
 
    int x = 1;
    for (int i = 0; i 0)
            prefixHash[i]
                = (prefixHash[i]
                + prefixHash[i - 1])
                % MOD;
 
        // Compute inverse modulo
        // of P ^ i for division
        // using Fermat Little theorem
        inversePrefix[i] = power(x, MOD - 2,
                                MOD);
 
        x = (1LL * x * P) % MOD;
    }
 
    x = 1;
 
    // Calculate suffix hash
    for (int i = n - 1; i >= 0; i--) {
 
        // Calculate and store hash
        suffixHash[i]
            = (1LL * int(s[i]
                        - 'a' + 1)
            * x)
            % MOD;
 
        if (i 0
                ? prefixHash[l - 1]
                : 0);
    h = (h + MOD) % MOD;
    h = (1LL * h * inversePrefix[l])
        % MOD;
 
    return h;
}
 
// Function to return Suffix
// Hash of substring
int getSuffixHash(int l, int r)
{
    // Calculate suffix hash
    // from l to r
    int h = suffixHash[l]
            - (r < n - 1
                ? suffixHash[r + 1]
                : 0);
 
    h = (h + MOD) % MOD;
    h = (1LL * h * inverseSuffix[r])
        % MOD;
 
    return h;
}
 
int numWays(string& s)
{
    n = s.length();
 
    // Compute prefix and
    // suffix hashes
    preCompute(s);
 
    // Stores the number of
    // possible splits
    int ans = 0;
    for (int i = 0;
        i < n - 1; i++) {
 
        int preHash = getPrefixHash(0, i);
        int sufHash = getSuffixHash(0, i);
 
        // If the substring s[0]...s[i]
        // is not palindromic
        if (preHash != sufHash)
            continue;
 
        preHash = getPrefixHash(i + 1,
                                n - 1);
        sufHash = getSuffixHash(i + 1,
                                n - 1);
 
        // If the substring (i + 1, n - 1)
        // is not palindromic
        if (preHash != sufHash)
            continue;
 
        // If both are palindromic
        ans++;
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    string s = "aaaaa";
 
    int ans = numWays(s);
 
    cout << ans << endl;
 
    return 0;
}
 
 

Java




// Java Program to implement
// the above approach
 
import java.util.*;
 
public class Main {
     
    // Modulo for rolling hash
    static final int MOD = 1_000_000_007;
     
    // Small prime for rolling hash
    static final int P = 37;
     
    // Maximum length of string
    static final int MAXN = 100_005;
     
    // Stores prefix hash
    static int[] prefixHash = new int[MAXN];
     
    // Stores suffix hash
    static int[] suffixHash = new int[MAXN];
     
    // Stores inverse modulo
    // of P for prefix
    static int[] inversePrefix = new int[MAXN];
     
     
    // Stores inverse modulo
    // of P for suffix
    static int[] inverseSuffix = new int[MAXN];
 
    static int n;
     
     
    static int power(int x, int y, int mod) {
        // Function to compute
        // power under modulo
        if (x == 0)
            return 0;
 
        int ans = 1;
        while (y > 0) {
            if ((y & 1) == 1)
                ans = (int)(((long)ans * x) % mod);
 
            x = (int)(((long)x * x) % mod);
            y >>= 1;
        }
        return ans;
    }
     
    // Precompute hashes for the
    // given string
    static void preCompute(String s) {
        int x = 1;
        for (int i = 0; i < n; i++) {
            prefixHash[i] = (int)(((long)(s.charAt(i) - 'a' + 1) * x) % MOD);
             
            // Compute inverse modulo
            // of P ^ i for division
            // using Fermat Little theorem
            if (i > 0)
                prefixHash[i] = (prefixHash[i] + prefixHash[i - 1]) % MOD;
 
            inversePrefix[i] = power(x, MOD - 2, MOD);
 
            x = (int)(((long)x * P) % MOD);
        }
 
        x = 1;
         
        // Calculate suffix hash
        for (int i = n - 1; i >= 0; i--) {
             
             
            // Calculate and store hash
            suffixHash[i] = (int)(((long)(s.charAt(i) - 'a' + 1) * x) % MOD);
            if (i < n - 1)
                suffixHash[i] = (suffixHash[i] + suffixHash[i + 1]) % MOD;
 
            inverseSuffix[i] = power(x, MOD - 2, MOD);
 
            x = (int)(((long)x * P) % MOD);
        }
    }
 
    static int getPrefixHash(int l, int r) {
        int h = prefixHash[r];
        if (l > 0)
            h = (h - prefixHash[l - 1] + MOD) % MOD;
 
        h = (int)(((long)h * inversePrefix[l]) % MOD);
 
        return h;
    }
     
    // Function to return Suffix
    // Hash of substring
    static int getSuffixHash(int l, int r) {
         
        int h = suffixHash[l];
        if (r < n - 1)
            h = (h - suffixHash[r + 1] + MOD) % MOD;
 
        h = (int)(((long)h * inverseSuffix[r]) % MOD);
 
        return h;
    }
 
    static int numWays(String s) {
        n = s.length();
         
        // Calculate suffix hash
        // from l to r
        preCompute(s);
 
         
        // Stores the number of
        // possible splits
        int ans = 0;
        for (int i = 0; i < n - 1; i++) {
            int preHash = getPrefixHash(0, i);
            int sufHash = getSuffixHash(0, i);
             
            // If the substring s[0]...s[i]
            // is not palindromic
            if (preHash != sufHash)
                continue;
 
            preHash = getPrefixHash(i + 1, n - 1);
            sufHash = getSuffixHash(i + 1, n - 1);
             
             
            // If the substring (i + 1, n - 1)
            // is not palindromic
            if (preHash != sufHash)
                continue;
             
            // If both are palindromic
            ans++;
        }
        return ans;
    }
     
    // Driver Code
    public static void main(String[] args) {
        String s = "aaaaa";
 
        int ans = numWays(s);
 
        System.out.println(ans);
    }
}
 
// Contributed by adityasha4x71
 
 

Python3




# Python Program to implement
# the above approach
 
# Modulo for rolling hash
MOD = 10**9 + 9
 
# Small prime for rolling hash
P = 37
 
# Maximum length of string
MAXN = 10**5 + 5
 
# Stores prefix hash
prefixHash = [0] * MAXN
 
# Stores suffix hash
suffixHash = [0] * MAXN
 
# Stores inverse modulo
# of P for prefix
inversePrefix = [0] * MAXN
 
# Stores inverse modulo
# of P for suffix
inverseSuffix = [0] * MAXN
 
 
def power(x, y, mod):
    # Function to compute
    # power under modulo
    if x == 0:
        return 0
 
    ans = 1
    while y > 0:
        if y & 1:
            ans = (ans * x) % mod
 
        x = (x * x) % mod
        y >>= 1
    return ans
 
# Precompute hashes for the
# given string
def preCompute(s):
 
    global prefixHash, suffixHash, inversePrefix, inverseSuffix, P, MOD
 
    x = 1
    for i in range(len(s)):
 
        # Calculate and store hash
        prefixHash[i] = ((ord(s[i]) - ord('a') + 1) * x) % MOD
 
        # Calculate prefix sum
        if i > 0:
            prefixHash[i] = (prefixHash[i] + prefixHash[i - 1]) % MOD
 
        # Compute inverse modulo
        # of P ^ i for division
        # using Fermat Little theorem
        inversePrefix[i] = power(x, MOD - 2, MOD)
 
        x = (x * P) % MOD
 
    x = 1
 
    # Calculate suffix hash
    for i in range(len(s) - 1, -1, -1):
 
        # Calculate and store hash
        suffixHash[i] = ((ord(s[i]) - ord('a') + 1) * x) % MOD
 
        if i < len(s) - 1:
            suffixHash[i] = (suffixHash[i] + suffixHash[i + 1]) % MOD
 
        # Compute inverse modulo
        # of P ^ i for division
        # using Fermat Little theorem
        inverseSuffix[i] = power(x, MOD - 2, MOD)
 
        x = (x * P) % MOD
 
# Function to return Prefix
# Hash of substring
def getPrefixHash(l, r):
 
    global prefixHash, inversePrefix, P, MOD
 
    # Calculate prefix hash
    # from l to r
    h = prefixHash[r] - (prefixHash[l - 1] if l > 0 else 0)
    h = (h + MOD) % MOD
    h = (h * inversePrefix[l]) % MOD
 
    return h
 
# Function to return Suffix
# Hash of substring
def getSuffixHash(l, r):
 
    global suffixHash, inverseSuffix, P, MOD
 
    # Calculate suffix hash
    # from l to r
    h = suffixHash[l] - (suffixHash[r + 1] if r < len(suffixHash) - 1 else 0)
    h = (h + MOD) % MOD
    h = (h * inverseSuffix[r]) % MOD
 
    return h
 
def numWays(s):
 
    global n, preHash, sufHash
    n = len(s)
 
    # Compute prefix and
    # suffix hashes
    preCompute(s)
 
    # Stores the number of
    # possible splits
    ans = 0
    for i in range(n - 1):
 
        preHash = getPrefixHash(0, i)
        sufHash = getSuffixHash(0, i)
 
        # If the substring s[0]...s[i]
        # is not palindromic
        if (preHash != sufHash):
            continue
 
        preHash = getPrefixHash(i + 1,
                                n - 1)
        sufHash = getSuffixHash(i + 1,
                                n - 1)
 
        # If the substring (i + 1, n - 1)
        # is not palindromic
        if (preHash != sufHash):
            continue
 
        # If both are palindromic
        ans += 1
    return ans
 
# Driver Code
s = "aaaaa"
ans = numWays(s)
print(ans)
 
 

C#




// C# program for the above approach
using System;
 
public class GFG
{
  // Modulo for rolling hash
  static readonly int MOD = 1_000_000_007;
 
  // Small prime for rolling hash
  static readonly int P = 37;
 
  // Maximum length of string
  static readonly int MAXN = 100_005;
 
  // Stores prefix hash
  static int[] prefixHash = new int[MAXN];
 
  // Stores suffix hash
  static int[] suffixHash = new int[MAXN];
 
  // Stores inverse modulo
  // of P for prefix
  static int[] inversePrefix = new int[MAXN];
 
 
  // Stores inverse modulo
  // of P for suffix
  static int[] inverseSuffix = new int[MAXN];
 
  static int n;
 
  // Function to compute
  // power under modulo
  static int power(int x, int y, int mod)
  {
    if (x == 0)
      return 0;
 
    int ans = 1;
    while (y > 0)
    {
      if ((y & 1) == 1)
        ans = (int)(((long)ans * x) % mod);
 
      x = (int)(((long)x * x) % mod);
      y >>= 1;
    }
    return ans;
  }
 
  // Precompute hashes for the
  // given string
  static void preCompute(string s)
  {
    int x = 1;
    for (int i = 0; i < n; i++)
    {
      prefixHash[i] = (int)(((long)(s[i] - 'a' + 1) * x) % MOD);
 
      // Compute inverse modulo
      // of P ^ i for division
      // using Fermat Little theorem
      if (i > 0)
        prefixHash[i] = (prefixHash[i] + prefixHash[i - 1]) % MOD;
 
      inversePrefix[i] = power(x, MOD - 2, MOD);
 
      x = (int)(((long)x * P) % MOD);
    }
 
    x = 1;
 
    // Calculate suffix hash
    for (int i = n - 1; i >= 0; i--)
    {
      // Calculate and store hash
      suffixHash[i] = (int)(((long)(s[i] - 'a' + 1) * x) % MOD);
      if (i < n - 1)
        suffixHash[i] = (suffixHash[i] + suffixHash[i + 1]) % MOD;
 
      inverseSuffix[i] = power(x, MOD - 2, MOD);
 
      x = (int)(((long)x * P) % MOD);
    }
  }
 
 
  // Function to return Prefix
  // Hash of substring
  static int getPrefixHash(int l, int r)
  {
    int h = prefixHash[r];
    if (l > 0)
      h = (h - prefixHash[l - 1] + MOD) % MOD;
 
    h = (int)(((long)h * inversePrefix[l]) % MOD);
 
    return h;
  }
 
  // Function to return Suffix
  // Hash of the substring
  static int getSuffixHash(int l, int r)
  {
    int h = suffixHash[l];
    if (r < n - 1)
      h = (h - suffixHash[r + 1] + MOD) % MOD;
 
    h = (int)(((long)h * inverseSuffix[r]) % MOD);
 
    return h;
  }
 
  static int numWays(string s)
  {
    n = s.Length;
 
    // Calculate suffix hash
    // from l to r
    preCompute(s);
 
    // Stores the number of
    // possible splits
    int ans = 0;
    for (int i = 0; i < n - 1; i++)
    {
      int preHash = getPrefixHash(0, i);
      int sufHash = getSuffixHash(0, i);
 
      // If the substring s[0]...s[i]
      // is not palindromic
      if (preHash != sufHash)
        continue;
 
      preHash = getPrefixHash(i + 1, n - 1);
      sufHash = getSuffixHash(i + 1, n - 1);
 
 
      // If the substring (i + 1, n - 1)
      // is not palindromic
      if (preHash != sufHash)
        continue;
 
 
      // If both are palindromic
      ans++;
    }
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    string s = "aaaaa";
 
    int ans = numWays(s);
 
    Console.WriteLine(ans);
  }
}
 
 
// This code is contributed by princekumaras
 
 

Javascript




// Modulo for rolling hash
const MOD = BigInt(10 ** 9 + 9);
 
// Small prime for rolling hash
const P = BigInt(37);
 
// Maximum length of string
const MAXN = 10 ** 5 + 5;
 
// Stores prefix hash
const prefixHash = new Array(MAXN).fill(0n);
 
// Stores suffix hash
const suffixHash = new Array(MAXN).fill(0n);
 
// Stores inverse modulo
// of P for prefix
const inversePrefix = new Array(MAXN).fill(0n);
 
// Stores inverse modulo
// of P for suffix
const inverseSuffix = new Array(MAXN).fill(0n);
 
function power(x, y, mod) {
  // Function to compute
  // power under modulo
  if (x == 0n) {
    return 0n;
  }
 
  let ans = 1n;
  while (y > 0) {
    if (y & 1n) {
      ans = (ans * x) % mod;
    }
 
    x = (x * x) % mod;
    y >>= 1n;
  }
  return ans;
}
 
// Precompute hashes for the
// given string
function preCompute(s) {
  let x = 1n;
  for (let i = 0; i < s.length; i++) {
    // Calculate and store hash
    prefixHash[i] = ((BigInt(s.charCodeAt(i) - "a".charCodeAt(0) + 1) * x) % MOD);
 
    // Calculate prefix sum
    if (i > 0) {
      prefixHash[i] = (prefixHash[i] + prefixHash[i - 1]) % MOD;
    }
 
    // Compute inverse modulo
    // of P ^ i for division
    // using Fermat Little theorem
    inversePrefix[i] = power(x, MOD - 2n, MOD);
 
    x = (x * P) % MOD;
  }
 
  x = 1n;
 
  // Calculate suffix hash
  for (let i = s.length - 1; i >= 0; i--) {
    // Calculate and store hash
    suffixHash[i] = ((BigInt(s.charCodeAt(i) - "a".charCodeAt(0) + 1) * x) % MOD);
 
    if (i < s.length - 1) {
      suffixHash[i] = (suffixHash[i] + suffixHash[i + 1]) % MOD;
    }
 
    // Compute inverse modulo
    // of P ^ i for division
    // using Fermat Little theorem
    inverseSuffix[i] = power(x, MOD - 2n, MOD);
 
    x = (x * P) % MOD;
  }
}
 
// Function to return Prefix
// Hash of substring
function getPrefixHash(l, r) {
  // Calculate prefix hash
  // from l to r
  let h = prefixHash[r] - (prefixHash[l - 1n] || 0n);
  h = (h + MOD) % MOD;
  h = (h * inversePrefix[l]) % MOD;
 
  return h;
}
 
// Function to return Suffix
// Hash of substring
function getSuffixHash(l, r) {
  // Calculate suffix hash
  // from l to r
  let h = suffixHash[l] - (suffixHash[r + 1] || 0n);
  h = (h + MOD) % MOD;
  h = (h * inverseSuffix[r]) % MOD;
 
  return h;
}
 
function numW
 
 

Time Complexity: O(N * log(109)) 
Auxiliary Space: O(N)

Approach Name: Split String into Palindromes

Steps:

  1. Define a function named count_palindrome_splits that takes a string S as input.
  2. Initialize a variable count to 0.
  3. Loop through each possible index i to split the string from 1 to len(S)-1.
  4. Check if both the substrings formed by the split are palindromes.
  5. If yes, increment count.
  6. Return the count.

C++




#include <iostream>
#include <string>
 
using namespace std;
 
bool is_palindrome(string s)
{
    return s == string(s.rbegin(), s.rend());
}
 
int count_palindrome_splits(string S)
{
    int count = 0;
    for (int i = 1; i < S.length(); i++) {
        string left_substring = S.substr(0, i);
        string right_substring = S.substr(i);
        if (is_palindrome(left_substring)
            && is_palindrome(right_substring)) {
            count++;
        }
    }
    return count;
}
 
int main()
{
    string S = "aaaaa";
    cout << count_palindrome_splits(S) << endl; // Output: 4
    return 0;
}
 
 

Java




import java.util.*;
 
public class Main {
    public static boolean isPalindrome(String s)
    {
        return s.equals(
            new StringBuilder(s).reverse().toString());
    }
 
    public static int countPalindromeSplits(String S)
    {
        int count = 0;
        for (int i = 1; i < S.length(); i++) {
            String leftSubstring = S.substring(0, i);
            String rightSubstring = S.substring(i);
            if (isPalindrome(leftSubstring)
                && isPalindrome(rightSubstring)) {
                count++;
            }
        }
        return count;
    }
 
    public static void main(String[] args)
    {
        String S = "aaaaa";
        System.out.println(
            countPalindromeSplits(S)); // Output: 4
    }
}
 
 

Python3




def count_palindrome_splits(S):
    count = 0
    for i in range(1, len(S)):
        left_substring = S[:i]
        right_substring = S[i:]
        if is_palindrome(left_substring) and is_palindrome(right_substring):
            count += 1
    return count
 
 
def is_palindrome(s):
    return s == s[::-1]
 
 
# Example usage
S = "aaaaa"
print(count_palindrome_splits(S))  # Output: 4
 
 

C#




using System;
 
public class Program {
    public static int CountPalindromeSplits(string s)
    {
        int count = 0;
        for (int i = 1; i < s.Length; i++) {
            string leftSubstring = s.Substring(0, i);
            string rightSubstring = s.Substring(i);
            if (IsPalindrome(leftSubstring)
                && IsPalindrome(rightSubstring)) {
                count++;
            }
        }
        return count;
    }
 
    public static bool IsPalindrome(string s)
    {
        char[] charArray = s.ToCharArray();
        Array.Reverse(charArray);
        string reversedString = new string(charArray);
        return s == reversedString;
    }
 
    public static void Main()
    {
        string s = "aaaaa";
        Console.WriteLine(
            CountPalindromeSplits(s)); // Output: 4
    }
}
 
 

Javascript




//Funtion to check palindrome
function isPalindrome(s) {
  return s === s.split('').reverse().join('');
}
 
function countPalindromeSplits(S) {
  let count = 0;
  for (let i = 1; i < S.length; i++) {
  // finding the left and right substring
    let leftSubstring = S.substring(0, i);
    let rightSubstring = S.substring(i);
    if (isPalindrome(leftSubstring) && isPalindrome(rightSubstring)) {
      count++;
    }
  }
  return count;
}
 
// Main function
function main() {
  let S = "aaaaa";
   
  // Function call
  console.log(countPalindromeSplits(S)); // Output: 4
}
 
main();
 
 
Output
4   

Time Complexity: O(n^2) where n is the length of the input string S.

Auxiliary Space: O(n) where n is the length of the input string S.



Next Article
Check if concatenation of splitted substrings of two given strings forms a palindrome or not

I

insiderpants
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • Greedy
  • Hash
  • Pattern Searching
  • Strings
  • frequency-counting
  • Modular Arithmetic
  • palindrome
  • prefix
  • substring
  • Suffix-Array
Practice Tags :
  • Algorithms
  • Arrays
  • Greedy
  • Hash
  • Modular Arithmetic
  • palindrome
  • Pattern Searching
  • Strings

Similar Reads

  • Count of Palindrome Strings in given Array of strings
    Given an array of strings arr[] of size N where each string consists only of lowercase English letter. The task is to return the count of all palindromic string in the array. Examples: Input: arr[] = {"abc","car","ada","racecar","cool"}Output: 2Explanation: "ada" and "racecar" are the two palindrome
    5 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
    8 min read
  • Count of palindromic rows in given Matrix
    Given a matrix arr[][] of size N * N, the task is to find the number of palindromic rows. Examples: Input: arr[][] = {{1, 3, 1}, {2, 2, 3}, {2, 1, 2}} Output: 2Explanation: First and third row forms a palindrome i.e 1 3 1 and 2 1 2. Therefore, count of palindromic rows is 2. Input: arr[][] = {{2, 2,
    4 min read
  • Binary String of given length that without a palindrome of size 3
    Given an integer n. Find a string of characters 'a' and 'b' such that the string doesn't contain any palindrome of length 3. Examples: Input : 3 Output : "aab" Explanation: aab is not a palindrome. Input : 5 Output : aabba Explanation: aabba does not contain a palindrome of size 3. The approach here
    3 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"}. Sinc
    10 min read
  • Check given string is oddly palindrome or not | Set 2
    Given string str, the task is to check if characters at the odd indexes of str form a palindrome string or not. If not then print "No" else print "Yes". Examples: Input: str = "osafdfgsg", N = 9 Output: Yes Explanation: Odd indexed characters are = { s, f, f, s } so it will make palindromic string,
    12 min read
  • Minimum reduce operations to convert a given string into a palindrome
    Given a String find the minimum number of reduce operations required to convert a given string into a palindrome. In a reduce operation, we can change character to a immediate lower value. For example b can be converted to a. Examples : Input : abcd Output : 4 We need to reduce c once and d three ti
    4 min read
  • Count of leaf nodes of the tree whose weighted string is a palindrome
    Given an N-ary tree, and the weights which are in the form of strings of all the nodes, the task is to count the number of leaf nodes whose weights are palindrome. Examples: Input: 1(ab) / \ (abca)2 5 (aba) / \ (axxa)3 4 (geeks) Output: 2 Explanation: Only the weights of the leaf nodes "axxa" and "a
    7 min read
  • Count of non-palindromic strings of length M using given N characters
    Given two positive integers N and M, the task is to calculate the number of non-palindromic strings of length M using given N distinct characters. Note: Each distinct character can be used more than once. Examples: Input: N = 3, M = 2 Output: 6 Explanation: Since only 3 characters are given, those 3
    8 min read
  • Find the count of palindromic sub-string of a string in its sorted form
    Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences