Rearrange characters | Practice | GeeksforGeeks

Given a string S with repeated characters. The task is to rearrange characters in a string such that no two adjacent characters are the 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.
+1
patelbhargav9320026 days ago
 string rearrangeString(string s)
 {
        int n=s.length();
        sort(s.begin(),s.end());
        
        string ans=s;
        int c=0;
        for(int i=0;i<n;i+=2)
            ans[i]=s[c++];
        
        for(int i=1;i<n;i+=2)
            ans[i]=s[c++];
        
        for(int i=1;i<n;i++)
        {
            if(ans[i]==ans[i-1])
                return "-1";
        }
        
        return ans;
 }
+1
gaurabhkumarjha271020016 days ago
// c++
     unordered_map <char, int> m;
     priority_queue<pair <int,char> > p;
          
       for (auto c:s) m[c]++;
          
    for (auto x:m) p.push({x.second, x.first});
           
          string ans;
          
          while (p.size() > 1){
              
               auto top1= p.top(); p.pop();
               auto top2= p.top(); p.pop();
               
                ans+= top1.second;
                ans+= top2.second;
               top1.first--; top2.first--;
               
                if (top1.first > 0) p.push(top1);
                if (top2.first > 0) p.push(top2);
         }
         
            if (!p.empty()) {
                    
           if (p.top().first > 1) return "-1";
                    
                    else
                   ans+= p.top().second;
                } 
          
          return ans;
0
parthbabbar0011 month ago
string output = "";
        unordered_map<char,int> mp;
        priority_queue<pair<int,char> > pq;
        
        for(auto i : s){
            mp[i] += 1;
        }
        
        for(auto i:mp){
            pq.push({i.second,i.first});
        }
        
        while(pq.size()>1){
            pair<int,char> top1 = pq.top();
            pq.pop();
            pair<int,char> top2 = pq.top();
            pq.pop();
            
            output += top1.second;
            output += top2.second;
            
            if(--top1.first>0){
               pq.push(top1); 
            }
            if(--top2.first>0){
               pq.push(top2); 
            }
        }
        
        if(pq.size()){
            if(pq.top().first == 1){
                output += pq.top().second;
            }
            else{
                return "";
            }
        }
        
        return output;
0
navinkrsingh89812 months ago
******* O(n) solution with no extra space ******
 
string rearrangeString(string s)   {       //code here              int n = s.length();              int j=0;              for(int i=1; i<n; i++) // iterate in fwd direction       {           j = max(i, j);                      // find first element on i's right not matching to i's left neighbour           while(j < n && s[i-1] == s[j])                j++;                      if(j == n) // if no such neighbour exists then break;               break;                      //else swap element at i with element at j           char temp = s[i];           s[i] = s[j];           s[j] = temp;       }              // if the adjacent elements towards the last are not same then       // i will exceed j and loop will terminate and we have got the answer       if(j < n)           return s;                  // otherwise perform the same operation in reverse direction       for(int i=n-2; i>=0; i--)       {                      j = min(i, j);                      // find first element on i's left not matching to i's right neighbour           while(j >=0 && s[j] == s[i+1])               j--;                          //if no such neighbour exists then break           if(j == -1)               break;                      char temp = s[i];           s[i] = s[j];           s[j] = temp;         }              // if the adjacent elements towards the starting are not same then       // i will exceed j and loop will terminate and we have got the answer       if(j >= 0)           return s;       else // otherwise rearrangement is not possible;           return "-1";   }
+2
samrathbhatia3 months ago
class Solution{   public:   string rearrangeString(string s)   {    int n=s.size(),max=0;    map<char,int> m;    for(int i=0;i<s.size();i++)    {        m[s[i]]++;        if(max<m[s[i]])        max=m[s[i]];    }    if(max>(n+1)/2)return s="-1";    multimap<int,char,greater<int>> mp;    for(auto i:m)    {        mp.insert({i.second,i.first});    }    vector<char> v;    for(auto i:mp)    {        char x=i.second;        int count=i.first;        while(count>0)        {            v.push_back(x);            count--;        }    }    int l=-2;    for(int i=0;i<n;i++)    {        l+=2;        if(l>=n)l=1;        s[l]=v[i];    }    return s;   }   };
+1
arthurshelby3 months ago
😉🇮🇳✌️❄️
string rearrangeString(string s)
    {
        //code here
        map<char,int>m;
	   priority_queue<pair<int ,char>>pq;
	   for(auto &it:s)
	   m[it]++;
	   for(auto it:m)
	   pq.push({it.second,it.first});
	   s="";
	   while(!pq.empty())
	   {
	       pair<int,char>p1,p2;
	       p1=pq.top();
	       pq.pop();
	       p1.first--;
	       s=s+p1.second;
	       if(pq.size()>0){
	       p2=pq.top();
	       pq.pop();
	       s=s+p2.second;
	       p2.first--;
	       }
	       if(p1.first!=0)
	       pq.push(p1);
	       if(p2.first!=0)
	       pq.push(p2);
	   }
	   for(int i=0;i<s.size()-1;i++)
	   {
	       if(s[i]==s[i+1])
	       return "-1";
	   }
	   return s;
    }
+9
equbalzeeshan3 months ago
O(N) solution without priority_queue
Explanation: Consider this example: "aaabbbcdd", we will construct the string in this way:
a _ a _ a _ _ _ _    // fill in "a" at position 0, 2, 4a b a _ a _ b _ b  // fill in "b" at position 6, 8, 1a b a c a _ b _ b  // fill in "c" at position 3a b a c a d b d b // fill in "d" at position 5, 7
 
	string rearrangeString(string str)
    {
        int S = str.length();
        unordered_map<char, int> mp;
        
        char maxFreq;
        for(char ch : str) {
            mp[ch]++;
            if(mp[ch] > mp[maxFreq])
                maxFreq = ch;
        }
        
        if(mp[maxFreq] > (S + 1) / 2) return "-1";
        
        int idx = 0;
        while(mp[maxFreq]) {
            str[idx] = maxFreq;
            idx += 2;
            mp[maxFreq]--;
        }
        
        for(auto pr : mp) {
            char ch = pr.first;
            int cnt = pr.second;
            while(cnt > 0) {
                if(idx >= S) idx = 1;
                str[idx] = ch;
                idx += 2;
                cnt--;
            }
        }
        
        return str;
    }
+3
utkarshrdce3 months ago
  SOLUTION WITH DETAILED EXPLANATION
 
   we try to process first the one which comes the most number of times   if we have geeksforgeeks   initial frequency map : g - 2, e - 4, k - 2, s - 2, f - 1, o - 1, r - 1   initial ans = ""
   now we see that e comes most number of times, so pop it out   tp = (e, 4)   now as the answer is empty, push e at the back, and decrement the count of e -> (e, 3)   and push this one back into the priority queue
   now ans = "e"
   frequncy map Now : g - 2, e - 3, k - 2, s - 2, f - 1, o - 1, r - 1   again e is popped out   tp = (e, 3)   but now the last character in ans = e, so we cannot append e   so we will have to pop again from the pq (in case the pq has nothing, we return -1)   now the charactes with freq 2 is popped out tp2 = (g, 2)   add this to the answerr and decrement its count (g, 2) -> (g, 1), and push both the popped elements back into it (push tp1 and tp2)
 
class Solution
{
#define pci pair<char, int>
public:
   class Comp {
   public:
       bool operator()(pair<char, int> &p1, pair<char, int> &p2) {
           return p1.second < p2.second;
       }
   };

   string rearrangeString(string str)
   {
       //
       // priority_queue<pair<char, int>> pq;
       priority_queue<pci, vector<pci>, Comp> pq;
       unordered_map<char, int> mp;
       for (char c : str) mp[c]++;


       for (auto m : mp) {
           pq.push({m.first, m.second});
       }

       string ans = "";
       while (!pq.empty()) {
           auto tp = pq.top(); pq.pop();
           if (ans.empty() || ans.back() != tp.first) {
               ans.push_back(tp.first);
               tp.second--;
               if (tp.second > 0) pq.push(tp);
           } else {
               if (pq.empty()) return "-1";
               auto tp2 = pq.top(); pq.pop();
               ans.push_back(tp2.first); tp2.second--;
               if (tp2.second > 0) pq.push(tp2);
               if (tp.second > 0) pq.push(tp);
           }
       }
       return ans;
   }

};
 
0
utkarshrdce
This comment was deleted.
0
tahabasra924 months ago
 
class solution
{   public:   static bool comp(pair<int,char > a,pair<int,char> b){   if(a.first>b.first){       return true;   }   return false;} string rearrangeString(string &s){// Write your code here.   if(s.length()<=1){       return s;   }   unordered_map<char,int> m;   for(int i=0;i<s.length();i++){       m[s[i]]++;   }   vector<pair<int,char>> v;   for(auto it:m){       v.push_back({it.second,it.first});   }      sort(v.begin(),v.end(),comp);
       int x=0;    int it=v[0].first;       while(it-- ){           if(x>=s.length()){               return "-1";           }           x=x+2;       }       char ans[s.length()];   int i=0,k=0;   while(i<s.length()){       if(v[k].first==0){           k++;       }       ans[i]=v[k].second;       if(i+1 < s.length())           ans[i+1]='$';       v[k].first--;       i=i+2;   }          for(int j=0;j<s.length();j++){       if(ans[j]=='$'){           if(v[k].first == 0){               k++;           }           ans[j]=v[k].second;           v[k].first--;       }   }   string f="";    for(int j=0;j<s.length();j++){        f+=ans[j];    }     //cout<<f;   
  return f;      }
 
   };
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.