0

Given in an array n, I want to find all the distinct a, b, c elements such that a+b+c=0. For instance, imagine

n = [-1, 0, 1, 2, -1, -4]

result should be

[ [-1, 0, 1], [-1, -1, 2] ]

I came up with the following algorithm, which I think gives the complexity of O(n^2). My question is, can we make it more efficient computationally?

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Set<List<Integer>> collection = new HashSet<List<Integer>>();

        Arrays.sort(nums);

        int leadingPointer, tailPointer, container;
        for(int i=0; i<nums.length-2; i++){
            leadingPointer = i+1;
            tailPointer = nums.length-1;
            while(leadingPointer<tailPointer){
                container = nums[i] + nums[leadingPointer] + nums[tailPointer];
                if(container == 0){
                     collection.add(new ArrayList<Integer> (Arrays.asList(
                            nums[i],
                            nums[leadingPointer],
                            nums[tailPointer]
                    )));
                    tailPointer--;
                    leadingPointer++;
                } else if(container > 0){
                    tailPointer--;
                } else{
                    leadingPointer++;
                }
            }
        }

        List<List<Integer>> finalResult = new ArrayList<List<Integer>>();
        finalResult.addAll(collection);

        return finalResult;
    }
}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Hossein
  • 107
  • 1
  • 10
  • 1
    sounds to be a lot like subset-sum-problem. Its np-complete. https://en.wikipedia.org/wiki/Subset_sum_problem – man zet Dec 31 '19 at 10:57
  • 2
    This is an extension of the the [3SUM](https://en.wikipedia.org/wiki/3SUM) problem (where only the possibility to find one triple needs to be determined). There are sub-quadratic algorithms to solve 3SUM, but they are not trivial at all. – trincot Dec 31 '19 at 11:02

1 Answers1

0

Using nested loops, use each element of the set N as a . Now use each element of the set N excluding a as b. Now check if the set N excluding a and b contains the value -a - b if so add [a, b, -a -b] to the answer set. You may want to remove duplicates from the answer set if the question is to find distinct possibilities.

karmakaze
  • 34,689
  • 1
  • 30
  • 32