Skip to content

Added FourSumProblem.java #5786 #5853

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/main/java/com/thealgorithms/misc/FourSumProblem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please refactor the class name to be the same as the name of algorithm.

public List<List<Integer>> fourSum(int[] nums, int target) {
int n = nums.length;

List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);

// select the first element of the quadruplet
for (int i = 0; i < n; i++) {
// Skip duplicate
if (i > 0 && nums[i] == nums[i - 1]) continue;

// select the second element
for (int j = i + 1; j < n; j++) {
// Skip duplicate
if (j != i + 1 && nums[j] == nums[j - 1]) continue;
//assign two pointers
int k = j + 1;
int l = n - 1;

// Two-pointer approach to find the remaining two elements
while (k < l) {
// Calculate the sum of the current quadruplet
long sum = nums[i];
sum += nums[j];
sum += nums[k];
sum += nums[l];

if (sum == target) {
//if the sum matches the target store it in ans
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
temp.add(nums[l]);
ans.add(temp);

// Move both pointers
k++;
l--;

// skip duplicates for the third element & forth ele
while (k < l && nums[k] == nums[k - 1]) k++;
while (k < l && nums[l] == nums[l + 1]) l--;
}
else if (sum < target)
// If the sum < target, move the left pointer (k) to increase the sum
//bcz array is in sorting order so next element always greater
k++;
else
// If the sum > the target, move the right pointer (l) to decrease the sum
//bcz array is in sorting order so previous element of 'l' pointer always smaller
l--;
}
}
}
return ans;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also please add tests.

}
}
Loading