0015 - 3 Sum

0015 - 3 Sum

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Examples

Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]

Input: nums = [] Output: []

Input: nums = [0] Output: []

Constraints

0 <= nums.length <= 3000 -105 <= nums[i] <= 105

Java Solution

Two Pointer (Using Sort)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);

        List<List<Integer>> result = new ArrayList<>();

        for(int i = 0; i < nums.length - 2; i++) {
            if(i == 0 || (i > 0 && nums[i] != nums[i-1])) {
                int left = i+1;
                int right = nums.length-1;
                
                while(left < right) {
                    if(nums[i] + nums[left] + nums[right] == 0) {
                        while(left < right && nums[left] == nums[left+1]) left++;
                        while(left < right && nums[right] == nums[right-1]) right--;
                        
                        result.add(Arrays.asList(nums[i], nums[left], nums[right]));            
                        left++;
                        right--;  
                    } 
                    else if(nums[i] + nums[left] + nums[right] > 0)  right--;
                    else left++;
                }
            }
        }
        return result;
    }
}

HashSet (Using Sort)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        
        List<List<Integer>> result = new ArrayList<>();
        
        for(int i = 0; i < nums.length; i++) {
            if(i == 0 || nums[i-1] != nums[i]) twoSum(nums, i, result);
        }
        return result;
    }
    
    void twoSum(int[] nums, int i, List<List<Integer>> result) {
        Set<Integer> seen = new HashSet<>();
        for(int j = i + 1; j < nums.length; j++) {
            int complement = -nums[i] - nums[j];
            if(seen.contains(complement)) {
                result.add(Arrays.asList(nums[i], nums[j], complement));
                while(j+1 < nums.length && nums[j] == nums[j+1]) j++;
            }
            seen.add(nums[j]);
        }
    }
}

Last updated