Thursday, November 6, 2014

Facebook: Find all 3 items that sum to 0 in an array

Find all 3 items that sum to 0 in an array
Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

Code (Java):
public class Solution {
    public List<List<Integer>> threeSum(int[] sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (sum == null || sum.length < 3) {
            return result;
        }
        
        Arrays.sort(sum);
        
        for (int i = 0; i < sum.length - 2; i++) {
            if (i != 0 && sum[i] == sum[i - 1]) {
                continue;
            }
            
            int lo = i + 1;
            int hi = sum.length - 1;
            
            while (lo < hi) {
                int total = sum[i] + sum[lo] + sum[hi];
                
                if (total == 0) {
                    List<Integer> temp = new ArrayList<Integer>();
                    temp.add(sum[i]);
                    temp.add(sum[lo]);
                    temp.add(sum[hi]);
                    result.add(temp);
                    lo++;
                    hi--;
                
                    while (lo < hi && sum[lo] == sum[lo - 1]) {
                        lo++;
                    }
                
                    while (lo < hi && sum[hi] == sum[hi + 1]) {
                        hi--;
                    }
                } else if (total > 0) {
                    hi--;
                } else {
                    lo++;
                }
            }
        }
        
        return result;
    }
}

No comments:

Post a Comment