![]() |
VOOZH | about |
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:
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:
PrefixHash[l - r] = SuffixHash[l - r]
Below is the implementation of the above approach:
Time Complexity: O(N * log(109))
Auxiliary Space: O(N)
Steps:
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.