4

I have been struggling with this questions for sometime now. The question goes like this:-

We have n^2 numbers. We need to find out if there exists a triplet a,b,c such that a+b+c = 0. For a more generic case, a+b+c = k. (k is given)

There exists a solution with O(n^2log(n)) complexity.

Any help would be greatly appreciated.

thanks

Pigol
  • 1,081
  • 2
  • 12
  • 17
  • 1
    You may want to read existing literature on the subset sum problem, which is a more general version of what you are proposing. http://en.wikipedia.org/wiki/Subset_sum_problem – mqp Dec 15 '09 at 06:05
  • Just out of curiosity, is this for Project Euler? – Carl Smotricz Dec 15 '09 at 06:11
  • nope this is not for project euler. This problem was asked in one of my exams a couple for years back. – Pigol Dec 15 '09 at 06:21
  • are the N numbers unique, or are there duplicates? And: (a != b) && (a != c) ? –  Dec 15 '09 at 07:48
  • 1
    What do you mean by n^2 numbers? What is n? – MAK Dec 15 '09 at 07:51
  • the numbers may or may not be unique. n^2 = square(n). – Pigol Dec 15 '09 at 08:33
  • Your answer is here: http://stackoverflow.com/questions/2070359/finding-three-elements-in-an-array-whose-sum-is-closest-to-an-given-number – Steve Oct 08 '14 at 00:32

2 Answers2

3

To get this in O(n²logn), you'd have to sort the numbers. Find all combinations of 2 numbers, and do a binary search to find the third.

The upper bound is much higher for the general version of the problem.

Anurag
  • 132,806
  • 34
  • 214
  • 257
0

I wrote a rough solution.

It can definitely be done in O(n^2). You don't have to sort this.

It's an extension of the problem which requires summing two numbers to x and the trick is to use the hash table.

def triplets(l, total):
    """Sum of 3 numbers to get to total 
    Basically an extension of the 2 table 
    """
    l = set( l)
    d = { }

    for i in l:
        remain = total - i

        inside = {}
        for j in l:
            if i == j:
                continue
            inside[j] = remain -j

        d[i] = inside

    good = set()

    for first, dic in d.iteritems():
        for second, third in dic.iteritems():
            if third in l:
                good.add( tuple(sorted([first, second, third])) )

    for each in good: 
        print each

triplets( [2, 3, 4, 5, 6], 3+4+5)

NOTE: we can use a fast sorting method for triplets which will be O(1).

disappearedng
  • 6,800
  • 9
  • 53
  • 100