I was just wondering if any other logic is possible for this problem:
Question : Find the number of pairs in a given string and output the sum of all the pairs and the unpaired elements. PS: The input is case sensitive.
Example O/P:
eeqe 3
aaaa
2
rwertr
5
I figured out the solution to this problem by first sorting the input string and then comparing adjacent elements as shown in the code below:
int main()
{
int t,count=0,pos=0;
char swap;
char a[201];
cin>>a;
int len=strlen(a);
//cout<<a<<endl;
for (int c = 0 ; c < ( len - 1 ); c++)
{
for (int d = 0 ; d < len - c - 1; d++)
{
if (a[d] > a[d+1]) /* For decreasing order use < */
{
swap = a[d];
a[d] = a[d+1];
a[d+1] = swap;
}
}
}
//cout<<a<<endl;
count=0;
for(int i=0;i<len;){
if(a[i]==a[i+1]){
count++;
i+=2;
//if(i== len-2)i++;
}
else{ count++; i++;}
}
//if(a[len-1]!=a[len-2])count++;
cout<<count<<endl;
return 0;
}
This code works fine. But, I was just wondering if there is any other efficient solution to this problem that doesn’t involve sorting the entire input array.
It basically avoids sorting based on the idea that there are only 256 possible chars, so it’s sufficent to count them.This is my solution:
If, for example, the string contains 5 times an
'a', this allows 5/2 pairs (integer division) and 1 remains unpaired (because 5 is odd => 5%2 is 1)Edit: Because we are here in SO: