Lexicographically smallest permutation of a string with given subsequences
Given a string consisting only of two lowercase characters and and two numbers and . The task is to print the lexicographically smallest permutation of the given string such that the count of subsequences of is and of is . If no such string exists, print “Impossible” (without quotes).
Input: str = "yxxyx", p = 3, q = 3 Output: xyxyx Input: str = "yxxy", p = 3, q = 2 Output: Impossible
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.
Approach: First of all, by induction it can prove that the product of count of ‘x’ and count of ‘y’ should be equal to the sum of the count of a subsequence of ‘xy’ and ‘yx’ for any given string. If this does not hold then the answer is ‘Impossible’ else answer always exist.
Now, sort the given string so the count of a subsequence of ‘yx’ becomes zero. Let nx be the count of ‘x’ and ny be count of ‘y’. let a and b be the count of subsequence ‘xy’ and ‘yx’ respectively, then a = nx*ny and b = 0. Then, from beginning of the string find the ‘x’ which has next ‘y’ to it and swap both untill you reach end of the string. In each swap a is decremented by 1 and b is incremented by 1. Repeat this until the count of a subsequence of ‘yx’ is achieved i:e a becomes p and b becomes q.
Below is the implementation of the above approach:
Time Complexity: O(N2)