VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-characters-string-no-two-adjacent/

⇱ Rearrange characters in a String such that no two adjacent characters are same - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange characters in a String such that no two adjacent characters are same

Last Updated : 17 Feb, 2025

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 Possible

Input: s = "aaaabc" 
Output: ""
Explanation: Not Possible

[Approach 1] Using Max Heap - O(n*log n) Time and O(n) Space

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.


Output
acaba

[Approach 2] Using Greedy - O(n) Time and O(n) Space

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:

  • Calculate the frequencies of every character in the input string.
  • If a character with a maximum frequency has a frequency greater than (n + 1) / 2, then return an empty string, as it is not possible to construct the required string.
  • Now fill the even index positions with the maximum frequency character, if some even positions are remaining then first fill them with remaining characters.
  • Then fill odd index positions with the remaining characters.
  • Return the constructed string.

Output
abaca


Comment
Article Tags: