Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print “Not Possible“.
Input: str = “0000100001100001”, K = 4
Explanation: In the string “0001100000011000”, every 2K length substring becomes a palindrome whenever a K-length prefix is removed, until string length reduces to K.
Input: str = “100111”, K = 2
Output: “Not Possible”
Approach: Follow the steps below to solve the problem:
- Count the number of 0s and 1s present in the string. If the count of 0s or 1s is a multiple of N / K, then K reduction of the string is possible. Otherwise, print “Not Possible“.
- Initialize a string tempStr to store the initially formed lexicographically smallest 2K length string.
- Initialize a string finalStr to store the resultant string that satisfies the given conditions.
- Distribute the 0s into a segment of length 2K according to the below formula:
- No of zeroes in 2K length substring, N0 = ((Number of zeroes in N length string)/(Total length of the string))*(2K)
- No of ones in 2K length substring, N1 = (2*K – No of zeroes in 2K length substring)
- Append tempStr with 0s N0/2 times and with 1s N1/2 times and again with 0s N0/2 times.
- Append tempStr (N/2K) times to finalStr and insert (N%2K) characters of the tempStr at the end of the finalStr.
- Print finalStr as the resultant string.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.