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 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> |
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:
- 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 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(); |
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 neveropen!