Leaderboard
Showing:
Rearrange characters
Medium Accuracy: 43.8% Submissions: 615 Points: 4

Given a string S with repeated characters. The task is to rearrange characters in a string such that no two adjacent characters are same. Note: The string has only lowercase English alphabets and it can have multiple solutions. Return any one of them.

Example 1:

Input : 
str = "geeksforgeeks"
Output: 1
Explanation:
All the repeated characters of the 
given string can be rearranged so 
that no adjacent characters in the 
string is equal. Any correct 
rearrangement will show a output of 1.

Example 2:

Input : 
str = "bbbbb"
Output: 0
Explanation : 
Repeated characters in the string cannot 
be rearranged such that there should not 
be any adjacent repeated character.
Your task :
You don't have to read input or print anything. Your task is to complete the function rearrangeString() which takes the string as input and returns the modified string. If the string cannot be modified return "-1".
 
Expected Time Complexity : O(NlogN), N = length of String
Expected Auxiliary Space : O(number of english alphabets)
 
Constraints : 
1 <= length of string <= 104

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Rearrange characters

Output Window