


For a string “qaacde”, This string has two same adjacent characters.
So, one possible way to rearrange the string is “qacade”. Now, this string does not have two adjacent characters that are the same.
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first line of each test case contains a string S.
For each test case, the output will be “Yes” if you have returned the correct answer, else it will be “No”.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
0 <= |S| <= 10^5
Time Limit: 1 sec
In this approach, we will generate all the possible rearrangements of the string and check if the current string in our rearrangement does not have any two adjacent characters that are the same. If we can find any string which satisfies our criteria then we will return that string else we will return “not possible”.
We can implement the above approach by –
The idea is here to store the frequency of each character in a hashmap and then build a max heap of pairs containing the frequency of character and character.
We will always pick the highest frequency character that is not the same as the previously picked character from the max heap and add the picked character to the answer.
The idea is here to sort the string based on the frequency of characters and then merge characters one by one from the front and middle of the string using left and right pointers.
The idea here is to store the frequency of each character of a string in a frequency array.
Let’s consider the following two observations:
So we will fill maximum frequency characters first in even positions and then remaining characters at odd positions. If all even positions are filled then we will start filling from odd positions.