Search code examples
c++ordered-map

C++ map not deleting elements


Given a target K, and an array of distinct elements, the task is to remove all pairs from the array which sums to K.

This is the approach I followed

for(i=0;i<N;i++)
    cin>>array[i];
cin>>K;
map<int, int> mp;
for(i=0;i<N;i++)
{
    if(mp.find(array[i])==mp.end())
        mp[array[i]] = 1;
    else
        mp[array[i]]++;
}

Logic for deletion

for(i=0;i<N;i++)
{
   if(mp[K-array[i]]>0)
   {            
       mp.erase(K-array[i]);
       mp.erase(array[i]);
    }
}

Print output :

cout<<mp.size();

Input :

array = 6 5 4 2 1 0
K = 6

Program output

4

Expected Output

0

Solution

  • if(mp[K-array[i]]>0)
    

    std::map::operator::[] will add if element doesn't exists

    You will have to find and remove like following:

    for(int i=0;i<N;i++)
    {
       if(mp.find(K-array[i]) != mp.end()  && 
          K-array[i] != array[i])
          //~~~~~~~~~~~~~~~~~~~~~ check required to see k/2 = array[i]
          // Note: all numbers are distinct 
       { 
           mp.erase(K-array[i]);
           mp.erase(array[i]);
       }
    }
    

    A better strategy would be to use remove elements during scanning using std::unordered_set

    std::unordered_set<int> s;
    
    for(const auto& ele: array) {
        auto it =  s.find( K - ele);
        if ( it == s.end() ) {
         s.insert(ele);   
        } else {
            s.erase(it);
        }
    }
    
    std::cout << s.size();
    

    See here