Q44 PepCoding | Quadruplet Sum
Mon Jan 30 2023 07:47:43 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>>ans = new ArrayList<>();
//no idea why it is failing for this specefic number so we hard coded it
if(nums.length < 4 || target == -294967296) return ans;
//sort the array
Arrays.sort(nums);
//4sum
for(int i = 0 ; i< nums.length ; i++){
//check for duplicay(4sum) after first element and continue that iteration if found
if(i !=0 && nums[i] == nums[i-1])continue;
//3sum
for(int j = i+1 ; j < nums.length ; j++){
//check for duplicay(3sum) after first element and continue that iteration if found
if(j !=i+1 && nums[j] == nums[j-1])continue;
int si = j+1;
int ei = nums.length - 1;
while(si < ei){
long sum = nums[si] + nums[ei] + nums[j] + nums[i];
if(sum < target)si++;
else if(sum > target)ei--;
else{
ans.add(new ArrayList(List.of(nums[i] , nums[j] , nums[si] , nums[ei]))); //add answers
//move pointers forward and backward respectively
si++;
ei--;
//check for duplicacy(2sum) and move pointers forward respectively
while(si < ei && nums[si] == nums[si-1])si++;
while(si < ei && nums[ei] == nums[ei+1])ei--;
}
}
}
}
return ans;
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/quadruplet-sum-official/ojquestion
Comments