![]() |
VOOZH | about |
Given a string str of length N, and an integer K, the task is to form K different strings by choosing characters from the given string such that all the strings formed are palindrome and the length of the smallest string among the K strings is maximum possible.
Examples:
Input: str = "qrsprtps", K = 2
Output: 3
Explanation: The 2 strings are: "pqp" and " rssr".
Using 2 'p' and 1 'q' the 1st string is formed and using 2 'r' and 2 's' the 2nd string is formed.
The 1st string is the smallest among the K strings and is of length 3 so the answer is 3.Input: str = "aaaabcbabca", K = 3
Output: 3
Explanation: Possible 3 palindromic strings of maximum possible length are: "aba", "aba", "aba".
The length of the smallest string among these is 3.
Approach: The approach is based on the Greedy technique. Try to distribute a pair of same characters to K strings equally. Make pairs of identical characters to ensure the string formed will be a palindrome. An even length palindrome of length N will have N/2 such pairs and an odd length will have an extra character along with the N/2 pairs.
Below is the implementation of the above approach.
3
Time Complexity: O(N)
Auxiliary Space: O(N)