4Sum

 Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:


0 <= a, b, c, d < n

a, b, c, and d are distinct.

nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.


 


Example 1:


Input: nums = [1,0,-1,0,-2,2], target = 0

Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

Example 2:


Input: nums = [2,2,2,2,2], target = 8

Output: [[2,2,2,2]]



class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
       

        List<List<Integer>> result= new ArrayList<>();
        Arrays.sort(nums);
        int n=nums.length;

        for(int i=0;i<n-3;i++)
        {
            if(i > 0 && nums[i]==nums[i-1]) continue;
            for(int j=i+1;j<n-2;j++)
            {
               if(j> i+1 && nums[j]==nums[j-1]) continue;
                int start=j+1;
                int end=n-1;

                while(start < end)
                {
                   long sum = (long) nums[i]+nums[j]+nums[start]+nums[end];

                    if(sum ==target)
                    {
                        result.add(Arrays.asList(nums[i],nums[j],nums[start],nums[end]));
                       
                        // Skip duplicates for start and end
                        while (start < end && nums[start] == nums[start + 1]) start++;
                        while (start < end && nums[end] == nums[end - 1]) end--;

                        start++;
                        end--;
                    }
                    else if(sum < target)
                    {
                        start++;
                    }
                    else
                    {
                         end--;
                    }

                }
            }
        }

    return result;
    }
    }
;
   

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence