![]() |
VOOZH | about |
Given a string s with lowercase repeated characters, the task is to rearrange characters in a string so that no two adjacent characters are the same. If it is not possible to do so, then print empty string ("").
Note: Multiple valid rearranged strings can be possible for same input string.
Examples:
Input: s = "aaabc"
Output: abaca
Explanation: No two adjacent characters are same in the output string.Input: s = "aa"
Output: ""
Explanation: Not PossibleInput: s = "aaaabc"
Output: ""
Explanation: Not Possible
Table of Content
The idea is to place the highest frequency character first. We use a priority queue (max heap) and put all characters and ordered by their frequencies (highest frequency character at root). One by one take the highest frequency character from the heap and add it to result. After adding it, just decrease the frequency of the character and then temporarily move this character out of priority queue so that it is not picked again next time.
acaba
The idea is to fill all the even positions of the result string first, with the highest frequency character. If there are still some even positions remaining, fill them first. Once even positions are done, then fill the odd positions. This way, it can be ensured that no two adjacent characters are the same.
Follow the given steps to solve the problem:
abaca