Skip to content
Advertisement

Finding the number of distinct pairs of integers that sum up to an integer

I am trying to count the numbers of pairs in an array such that each pair gives the sum of an integer!

I used the following code :

JavaScript

the problem is ; for example when my array is 1 2 2 2 3 4 4 4 and sum = 5 it compute as following

JavaScript

I want to prevent the method from using a number more than once !! so the output will be

JavaScript

Advertisement

Answer

I use a map storing values and their frequencies:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement