Given a string ‘STR’ containing lowercase and uppercase letters. You need to sort the string so that the resulting string contains uppercase and lowercase letters at alternate positions but in sorted order.
NoteIf any lowercase or uppercase letters remains left after alternate positioning, then append them at the last of the string in sorted order.
For Example
If the given string STR = “rDaBfS” then after sorting STR = “aBfDrS”. In the sorted string, lowercase letters a,f,r, and uppercase letters B, D, S are in sorted order and alternate positions.
The first line contains ‘T’, denoting the number of test cases.
The first line of each test contains a string 'STR' containing lowercase and uppercase letters.
Output Format
For each test case, print a single line containing a single string denoting the sorted string having the lower case or uppercase letters at alternate positions.
The output for each test case will be printed in a separate line.
Note:
You don't have to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |STR| <= 10 ^ 5
Where ‘T’ is the number of test cases and |STR| is the string’s length.
Time limit: 1 sec.
2
pqrPQR
dBAAa
pPqQrR
aAdAB
Test Case 1: The lowercase letters in the given string ( p,q,r ) and uppercase letters (P, Q, R ) are in sorted order. After arranging them at alternate positions, the resulting string = “pPqQrR”.
Test Case 2: In the given string lowercase letters = d,a and uppercase letters = B,A,A
After sorting and alternate positioning string will become aAdAB. As in this case, we were left with an extra uppercase letter ‘B’, so we have appended it at last.
2
bauricn
rdMWcU
abcinru
cMdUrW
Sort uppercase and lowercase letters separately.
Algorithm
O(|STR|), where |STR| is the length of the string.
We are traversing the string once to store every letter’s count and then traversing to place the letters in alternate sorted order. Therefore the overall complexity of both the traversals is O(|STR|).
O(1).
We have used two arrays, ‘upCount’ and ‘lowCount’ of fixed size. So as we have used constant space, the space complexity is O(1).