String_compression

https://hack.codingblocks.com/contests/c/916/107

#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
cin>>s;
sort(s.begin(),s.end());
map<char,int> map;
int n=s.length();
if(n==0){
return 0;
}
for(int i=0;i<n;i++){
if(map.find(s[i])!=map.end()){
map[s[i]]++;
}
else
map[s[i]]=1;
}
if(n>0){
for(auto i:map){
cout<<i.first<<i.second;
}
}
return 0;
}

@gsinha783
You are assumming that the characters need to be printed in sorted order and that same character strings will occur together. However it is not so.
Input :
bbaabbb

Expected Output :
b2a2b3

Your Output :
a2b5

so will it work if I remove the sorting operation?

@gsinha783
Sorting is one of the problems. You shouldn’t sort it.
But as you can see for the above testcase , your code would still fail. You are considering all the a’s and b’s together using a map and counting their frequency. However we don’t need their entire frequency.
Take a look at the example I gave above.
bbaabbb
Your code will count all the b’s and produce the result like b5a2 since it does not distinguish between the b’s at the beginning or later. However the expected correct output is
b2a2b3

It should consider them seperately and give each’s count as seperate.
Remove the sorting but still you would have to make more changes. Basically you would need to change your entire approach as this one won’t work for this problem.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.