Is it possible to write a program to print all pairs that add to k from an input array of size n. If so how? I heard this problem is NP-Complete. I was wondering if we can provide a solution to this problem in typical programming languages like C/C++
Asked
Active
Viewed 503 times
-1
-
What do you have so far, and how doesn't it work? – Ignacio Vazquez-Abrams Jun 20 '11 at 03:13
-
Yes, it's possible. Have you tried anything? – zneak Jun 20 '11 at 03:14
-
I tried. But the algorithm is exponential. It is basically by checking out all combinations of the numbers in the array and comparing the sum with the value k. – Mike Jun 20 '11 at 03:15
-
If its NP complete, can you do better than exponential? – Adithya Surampudi Jun 20 '11 at 03:17
-
What should I say if I get this question in a job interview – Mike Jun 20 '11 at 03:18
-
Nope it is mathematically impossible to solve with a computer, you can only do it by hand – Woot4Moo Jun 20 '11 at 03:18
-
I heard there is an approximate algorithm for it. If anyone can explain then that would be useful. – Mike Jun 20 '11 at 03:19
-
I don't know why people have voted down and closed this. Anyways, you can read more about it on [Wikipedia](http://en.wikipedia.org/wiki/Subset_sum_problem). – Priyank Bhatnagar Jun 20 '11 at 06:52
-
Now, i know. The question is wrong. Sorry for all the hassle. – Priyank Bhatnagar Jun 20 '11 at 06:58
1 Answers
4
It can't be NP-Complete as there is an obvious O(n^2) solution with two nested loops over the array and checking if the sum is k.
There is however an O(n) solution using hashtable. Here is the solution in C#:
int[] ar = new int[] { 1, 4, 6, 8 };
int k = 7;
HashSet<int> set = new HashSet<int>();
foreach (int n in ar)
{
if (set.Contains(n))
Console.WriteLine("({0}, {1})", k - n, n);
set.Add(k - n);
}

Petar Ivanov
- 91,536
- 11
- 82
- 95
-
I am not sure that this will work. Can you provide a link to ideone, so that i can try to test your solution. I am not familiar with C#. – Priyank Bhatnagar Jun 20 '11 at 06:21
-
-
Ideone.com . This is a site where you can run your program. Sorry for not being clear. Submit your program in C# and give me the link. – Priyank Bhatnagar Jun 20 '11 at 06:38
-
[Code](http://ideone.com/ulRr6). Question asked was - "a program to print all pairs that add to k from an input array of size n." Answer should have been {(15), (1,4,4,6)}. – Priyank Bhatnagar Jun 20 '11 at 06:48
-
there is no pair that add up to 15 in the array (1,4,4,6,15), man. What are you talking about? pair = two :) – Petar Ivanov Jun 20 '11 at 06:53
-
Ah ! Sorry, with all the NP mentioned in the question, i deviated to a more general problem. My bad. – Priyank Bhatnagar Jun 20 '11 at 06:57