18. 4Sum(Solution || Leetcode medium || Java)
2 min readNov 18, 2022
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
, andd
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]]
Constraints:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
SOLUTION:
My solution also works on the testcase:-
Input
[1000000000,1000000000,1000000000,1000000000]
-294967296Output
[[1000000000,1000000000,1000000000,1000000000]]
Expected
[]
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
//First sort array as without sorting it will get too complex
Arrays.sort(nums);
//Create a list of list integer to store quadruplets
List<List<Integer>> output = new ArrayList<List<Integer>>();
//Special case for the above given testcase in the article
if(target < 0 && nums[0] > 0){
return output;
}
//Start looping through each element
for(int i = 0; i < nums.length - 3; i++){
//This condition is for skipping duplicates
if(i == 0 || (i > 0 && nums[i] != nums[i-1])){
//From here we will solve this question as we solved 3 Sum
//question using pointers
for(int j = i + 1; j < nums.length - 2; j++){
//This condition is same as above to skip duplicates
if(j == i+1 || (j > i+1 && nums[j] != nums[j-1])){
//First pointer
int low = j + 1;
//Second pointer
int high = nums.length - 1;
while(low < high){
//Sum of the quadruplets on which we are currently at
int currSum = nums[i] + nums[j] + nums[low] + nums[high];
//if any quad sum result in target add that quad in our list of list
if(currSum == target){
output.add(Arrays.asList(nums[i],nums[j],nums[low],nums[high]));
//Condition for skipping duplicates
while(low < high && nums[low] == nums[low+1]) low++;
while(low < high && nums[high] == nums[high -1])high--;
low++;
high--;
}
else if(currSum > target){
high--;
}
else{
low++;
}
}
}
}
}
}
return output;
}
}
Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.