How to find all the matching pairs in some random array using Hashmap in C ++

advertisements

I want to find all the pairs that in an array that sum upto a certain number X using Hashmap.I know the basic solution which has O(n^2) complexity but somewhere I read that hashmap can provide O(n) solution.I have no idea how can I use hashmap to achieve the solution.Can someone provide me a pseudo code on how to do that?


If you were to use something like a std::set, then all values in the set would be unique. This would allow you to loop through the set and do a subtraction from the desired value to determine the other value you would need. You can then test to see if that value exists in the set. The operations would look like this:

  1. Set iterator to first element in the set
  2. Get the value of the first element in the set
  3. Subtract the value from the desired value to obtain the needed value
  4. Test the set to see if the needed value is in the set
  5. If it is record both values
  6. Increment the iterator and repeat from #2 until you reach the end of the set