VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-ways-to-split-given-string-into-two-non-empty-palindromes/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

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:
Explanation:
Possible Splits: {"a", "aaaa"}, {"aa", "aaa"}, {"aaa", "aa"}, {"aaaa", "a"}
Input: S = "abacc" 
Output:
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:


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:

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.

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.

Comment