String compression

THIS CODE IS FAILING TWO TEST CASES WHAT IS WRONG HERE IN THIS CODE??
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[101],l,c;
int a[256]={0};
cin>>s;
l=strlen(s);
for (int i=0;i<l;i++)
{
a[s[i]]++;
}
for(int i=0;i<256;i++)
{
if(a[i]!=0)
{
c=char(i);
cout<<c<<a[i];
}
}

return 0;

}

Hi @sharma.shubham
See in the second for for loop you are printing char and its frequency in sorted order starting from a. For example :
If input is aaddbbg your code output is a2b2d2g1 but its correct output should be a2d2b2g2.
This is the reason why your two test cases are failing.

ok thnks i will correct it

I HAVE CORRECTED THE CODE NOW IT IS GIVING CORRECT OUTPUT AS YOU HAVE SUGGESTED BUT STILL 2 TEST CASES ARE NOT PASSING IS IT BECAUSE I HAVE NOT CREATED A FUNCTION FOR THIS (AS IN THE PROBLEM WE HAVE TO CREATE A FUNCTION FOR THIS).
CORRECTED CODE-
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[101],l;
int a[256]={0};
cin>>s;
l=strlen(s);
for (int i=0;i<l;i++)
{
a[s[i]]++;
}
for(int i=0;i<l;i++)
{

    if(s[i]!=s[i+1])
    {
    if(a[s[i]]!=0)
    {
        cout<<s[i]<<a[s[i]];

    }
}
}

return 0;

}

See the approach that you are using is calculating total occurrence of a character and then printing that character along with its count but for cases like aaabbaa your code is printing output as a5b2a5 but its correct output should be a3b2a2.

Here is the correct code for this problem have a look at it and try to understand :

1 Like