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
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)
- Lexicographically smallest permutation with no digits at Original Index
- Lexicographically n-th permutation of a string
- Find n-th lexicographically permutation of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Lexicographically smallest string of length N and sum K
- K-th lexicographically smallest unique substring of a given string
- Queries to answer the X-th smallest sub-string lexicographically
- Lexicographically smallest string formed by removing at most one character
- Find the lexicographically smallest string which satisfies the given condition
- Lexicographically smallest string obtained after concatenating array
- Swap all occurrences of two characters to get lexicographically smallest string
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s