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

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”.
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 notbool 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 splitsint 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 Codeint main(){ string S = "aaaaa"; cout << numWays(S); return 0;} |
Java
// Java program to implement// the above approachclass GFG{ // Function to check whether the// substring from l to r is// palindrome or notpublic 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 splitspublic 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 Codepublic 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 notdef 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 splitsdef 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 CodeS = "aaaaa"print(numWays(S))# This code is contributed by divyeshrabadiya07 |
C#
// C# program to implement// the above approachusing System;class GFG{ // Function to check whether the// substring from l to r is// palindrome or notpublic 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 splitspublic 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 Codepublic 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> |
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#includeusing namespace std;// Modulo for rolling hashconst int MOD = 1e9 + 9;// Small prime for rolling hashconst int P = 37;// Maximum length of stringconst int MAXN = 1e5 + 5;// Stores prefix hashvector prefixHash(MAXN);// Stores suffix hashvector suffixHash(MAXN);// Stores inverse modulo// of P for prefixvector inversePrefix(MAXN);// Stores inverse modulo// of P for suffixvector 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 stringvoid 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 substringint 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 Codeint main(){ string s = "aaaaa"; int ans = numWays(s); cout << ans << endl; return 0;} |
Java
// Java Program to implement// the above approachimport 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 hashMOD = 10**9 + 9# Small prime for rolling hashP = 37# Maximum length of stringMAXN = 10**5 + 5# Stores prefix hashprefixHash = [0] * MAXN# Stores suffix hashsuffixHash = [0] * MAXN# Stores inverse modulo# of P for prefixinversePrefix = [0] * MAXN# Stores inverse modulo# of P for suffixinverseSuffix = [0] * MAXNdef 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 stringdef 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 substringdef 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 substringdef 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 hdef 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 Codes = "aaaaa"ans = numWays(s)print(ans) |
C#
// C# program for the above approachusing 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 hashconst MOD = BigInt(10 ** 9 + 9);// Small prime for rolling hashconst P = BigInt(37);// Maximum length of stringconst MAXN = 10 ** 5 + 5;// Stores prefix hashconst prefixHash = new Array(MAXN).fill(0n);// Stores suffix hashconst suffixHash = new Array(MAXN).fill(0n);// Stores inverse modulo// of P for prefixconst inversePrefix = new Array(MAXN).fill(0n);// Stores inverse modulo// of P for suffixconst 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 stringfunction 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 substringfunction 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 substringfunction 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:
- Define a function named count_palindrome_splits that takes a string S as input.
- Initialize a variable count to 0.
- Loop through each possible index i to split the string from 1 to len(S)-1.
- Check if both the substrings formed by the split are palindromes.
- If yes, increment count.
- 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 countdef is_palindrome(s): return s == s[::-1]# Example usageS = "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 palindromefunction 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 functionfunction main() { let S = "aaaaa"; // Function call console.log(countPalindromeSplits(S)); // Output: 4}main(); |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


