DEV Community 👩‍💻👨‍💻

muTheTechie
muTheTechie

Posted on

How do you find all pairs of an integer array whose sum is equal to a given number?

input = [10,18,20,5,11,2,10,15]
sum = 20

length = len(input) 
for i in range(length): 
  for j in range(i+1, length):
    if(input[i] + input[j] == sum):
      print(input[i], input[j])
Enter fullscreen mode Exit fullscreen mode

and the output is

10 10
18 2
5 15
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
anduser96 profile image
Andrei Gatej

Another solution would be to use a map(or a dictionary in python, AFAIK) where each key would follow this rule: sum - list[i];

for (let i = 0; i < len; i++) {
   const k = sum-list[i];
  if (map.has(k))
     console.log(k, map.get(k))
  else map.set(k, list[i]);
}

Top Heroku Alternatives (For Free!)

Recently Heroku shut down free Heroku Dynos, free Heroku Postgres, and free Heroku Data for Redis on November 28th, 2022. So Meshv Patel put together some free alternatives in this classic DEV post.