Question: I wrote an function to determine if string `a` is a permutation of string `b`. The definition is as follows:

```
bool isPermutation(std::string a, std::string b){
    if(a.length() != b.length())
        return false;
    int a_sum, b_sum;
    a_sum = b_sum = 0;
    for(int i = 0; i < a.length(); ++i){
        a_sum += a.at(i);
        b_sum += b.at(i);
    }
    return a_sum == b_sum;
}

```

The issue with my approach is that if `a = 600000` and `b = 111111`, the function returns true.

Is there any way I can keep my general approach to this problem (as opposed to sorting the strings then doing `strcmp`) and maintain correctness?

Answer: 
You can count characters separately:

```
bool isPermutation(std::string a, std::string b)
{
    if(a.length() != b.length())
        return false;

    assert(a.length() <= INT_MAX);
    assert(b.length() <= INT_MAX);

    int counts[256] = {};
    for (unsigned char ch : a)
        ++counts[ch];
    for (unsigned char ch : b)
        --counts[ch];
    for (int count : counts)
        if (count)
            return false;

    return true;
}

```
```
std::sort( strOne.begin(), strOne.end() );
std::sort( strTwo.begin(), strTwo.end() );    
return strOne == strTwo;

```

will be sufficient.

---

My suggestion is to use `std::unordered_map`

i.e.

```
std::unordered_map< char, unsigned > umapOne;
std::unordered_map< char, unsigned > umapTwo;
for( char c : strOne ) ++umapOne[c];
for( char c : strTwo ) ++umapTwo[c];
return umapOne == umapTwo;

```

---

As an optimization you can add at the top for a solution

```
if( strOne.size() != strTwo.size() ) return false;

```

---

Better `std::unordered_map` solution,

```
if( strOne.size() != strTwo.size() ) return false; // required
std::unordered_map< char, int > umap;
for( char c : strOne ) ++umap[c];
for( char c : strTwo ) if( --umap[c] < 0 )  return false;
return true;

```

---

If you need to just solve a problem without knowing how to do it, you may use `std::is_permutation`

```
return std::is_permutation( strOne.begin(), strOne.end(), strTwo.begin(), strTwo.end() );

```