Making Anagrams

  • + 0 comments

    I increment the freq for each char from first array and decrement for each char for second array. The common chars therefore will cancel out. The ones that aren't common will either have a positive or negative value. When we add the absolute values we get the total number of different chars. My solution in c / c++. Using either arrays or unordered_map to store the freqeuncy:

    //std::unordered_map freq; const int range = 'z' - 'a' + 1; int freq[range] = {0};

    for(auto elem : s1)
    {
        //freq[elem]++;
        freq[elem - 'a']++;
    }
    for(auto elem : s2)
    {
        //freq[elem]--;
        freq[elem - 'a']--;
    }
    
    int sum = 0;
    //for(auto itr = freq.begin(); itr != freq.end(); itr++)
    for(auto idx = 0; idx < range; idx++)
    {
        //sum += abs(itr->second);
        sum += abs(freq[idx]);   
    }
    return sum;