REARRSTR - Editorial

can someone give me a test input where my code is failing… http://www.codechef.com/viewsolution/7048326

Can someone look, where my solution is failing.

http://www.codechef.com/viewsolution/7145091

Thanks!!

can someone check this why is it getting error SIGSEGV
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,k,l,o,p,m,n,x;
cin>>x;
while(x–)
{
int sum=0;
string s;
cin>>s;
int arr[26]={0};
multimap<int,int> mymap;
multimap<int,int>::iterator it,itr;
for(i=0;i<s.length();i++)
arr[s[i]-‘a’]++;
int maxi=0;
for(i=0;i<26;i++)
{
maxi=max(maxi,arr[i]);
sum+=arr[i];
mymap.insert(make_pair(arr[i],i)); //count,alphabet
}
if(maxi<=((sum+1)/2))
{
string s1;
i=0;
it=mymap.end();
while(it!=mymap.begin())
{
it–;
n=it->first;
while(n!=0)
{
s1[i]=char(it->second+‘a’);
i+=2;
if(i>=s.length())
i=1;
n–;
}
}
for(i=0;i<s.length();i++)
{
cout<<s1[i];
}
cout<<endl;
}
else
cout<<"-1"<<endl;
}
}

Can someone help me with my code? It is giving TLE. But time complexity is same as the solution.

The problem can be solved easily by using priority_queues. The queue stores the no. of occurrences(frequency) of a character and the character itself as a pair. Now you pop out the first two values from the queue. Decrease their occurrence frequency by 1 (until of course the frequency becomes 0) and add them to your final string and then again push the new pairs with updated frequencies. You do that till the priority queue becomes empty or it only has one element left, in which case you add the character of the remaining element its frequency number of times. Then just check your final string for equal adjacent characters. If so output -1 else you have your answer.

Here is the Link to my accepted code. View above solution.