Leetcode 3Sum problem solution in Java programming

In the Leetcode 3Sum problem solution in Java programming 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.

Leetcode 3Sum problem solution in Java programming

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums==null||nums.length<3)
            return res;    
        int n=nums.length;
        Arrays.sort(nums);
        for(int i=0;i<n-2;i++) {
            if(i>0 && nums[i]==nums[i-1])
                continue;
            int j=i+1;
            int k=n-1;
            while(j<k) {
                if(nums[i]+nums[j]+nums[k]==0) {
                    List<Integer> lis = new ArrayList<>();
                    lis.add(nums[i]);
                    lis.add(nums[j]);
                    lis.add(nums[k]);
                    res.add(lis);
                    j++;
                    k--;
                    while(j<k && nums[j]==nums[j-1])
                        j++;
                    while(j<k && nums[k]==nums[k+1])
                        k--;
                }else if(nums[i]+nums[j]+nums[k]<0) {
                    j++;
                }else {
                    k--;
                }
                    
            }
        }
        return res;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *