Given a string S, the task is to find the maximum number of palindromes that can be formed after performing the given steps:
- Choose a non-empty prefix P and a non-empty substring T of equal length.
- Reverse either P or T and concatenate them.
Note: P and T can be overlapping.
Input: S = “abab”
Consider prefix as S[0 : 1] ( = “ab“) and reverse the substring S[2 : 3]. Resultant string after concatenating prefix with reversed substring is “abba”, which is a palindrome.
All possible prefixes are [“a”, “ab”, ”aba”, ”abab”].
All possible suffixes are [“a”, ”b”, ”a”, ”b”, ”ab”, ”ba”, ”ab”, ”aba”, ”bab”, ”abab”].
Therefore, all possible palindromes are [“aa”, ”aa”, ”abba”, ”abba”, ”abaaba”, ”ababbaba”].
Input: S = “abcd”
Naive Approach: Generate all possible prefixes and all possible substrings. Concatenate all equal length prefix and substring(after reversing) pairs and check if the string obtained is palindrome or not.
Time Complexity: O(N3)
Auxiliary Space: O(N2)
Efficient Approach: The above approach can be optimized based on the observation that the length of the concatenated strings will always be even. Therefore, only those strings need to be considered in which the first half is the mirror image of the second half. Therefore, the problem reduces to counting substrings for every possible prefix which are equal to that prefix, which can be done using Z-function.
The z-function over a string will return an array Z where Z[i] represents the length of the longest prefix that same as the sub-string starting at position i and ending at position i+Z[i]. Hence the count will be .
Follow the steps below to solve the problem:
- The idea is to maintain an interval [l, r] which is the interval with max r such that [l, r] is a prefix substring (substring which is also prefix).
- If i ≤ r, then Z[i] is equal to minimum of r – i + 1 and Z[i – 1].
- Now, increment Z[i] until i + Z[i] is less than N and character at index Z[i] and i + Z[i] are equal in the given string.
- Now, if i + Z[i] – 1 > r, then set l to i and r to i + Z[i] – 1.
- Repeat the above steps for i from 0 to N-1.
- The answer is the sum of Z[i] + 1 for each i (0 ≤ i ≤ N-1).
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.