VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-the-minimum-length-of-k-palindromic-strings-formed-from-given-string/

⇱ Maximize the minimum length of K palindromic Strings formed from given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize the minimum length of K palindromic Strings formed from given String

Last Updated : 23 Jul, 2025

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. 

  • Count the frequency of the characters in the given string and the number of pairs that can be formed with those characters.
  • Distribute these pairs among K strings as long as there are K pairs available. (i.e. if there are 5 such pairs and K = 2 then, distribute 2 pairs to each so that a 4 length palindromic string can be formed single pair will be left undistributed)
  • Now there will be all even length palindromic strings. As the pairs left cannot be distributed among all the strings so the smallest string will have a length of twice the number of character pairs distributed to each of the strings.
  • Try to add 1 more character to see if an odd length string can be formed.
    • From the remaining characters i.e., the characters which were not a part of the pairs and the characters from the leftover pair of characters, add 1 character to each string to increase the maximum length by 1.
    • If there are at least K such characters present then only the minimum length can be increased by one for all strings.

Below is the implementation of the above approach.


Output
3

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment