-1

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++

Charles
  • 50,943
  • 13
  • 104
  • 142
Mike
  • 19

1 Answers1

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