Code showing Abort call despite code being completely fine

  anagram, c++, vector

I was just practicing problem-solving in Hackerrank and was solving the problem "anagram". Here, we had to divide a string and then perform some operations such that the the first string have all the elements of the second string with the same count. We have to count the number of operations that are require to make the first string anagram of the second string.

So, this was my solution for the problem:

int anagram(string s) {
int res=0;
string u;
string t;
vector<int> a(25);
vector<int> v(25);
int n = s.size();
if(n%2!=0)
{
    res = -1;
}
else
{
    t = s.substr(0,n/2);
    u = s.substr(n/2);
  
    for(int i=0;i<n/2;i++)
    {
        int temp = 'a' - t[i];
        a[temp]++;
    }
    
    for(int j=0;j<n/2;j++)
    {
        int tp = 'a' - u[j];
        v[tp]++;
    }
   
    for(int x=0;x<26;x++)
    {
        cout<<a[x]<<"a "<<v[x]<<"v ";
        if( v[x]!=0)
        {
            res+= abs(a[x]-v[x]);
        }
    }
    cout<<endl;
}
return res;
}

Here, if you notice you can see I am using counting sort method to store the count of alphabet letters at vector a and v. But the problem is I am able to store the count of alphabets of string t here, but when I am trying to store the values of string u in vector b, on the value for alphabet a is updating and rest are not.

here is an output of what happening:

3a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 0a 0v 

The digits which have a after them belongs to vector a while the digits which have v after them belongs to vector v. The index goes from 0 to 25 where 0 represents ‘a’ and 25 represents ‘z’. Also, it’s showing Abort call for some Testcases. Please help.

Source: Windows Questions C++

LEAVE A COMMENT