Skip to content
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
66 changes: 66 additions & 0 deletions src/main/java/com/thealgorithms/misc/FourSumProblemjava
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
* Problem Statement:
* 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:
*
* a, b, c, and d are distinct.
* nums[a] + nums[b] + nums[c] + nums[d] == target
*
*/

class FourSumProblem {

/**
* Given an array of integers, return the unique quadruplets that sums target
*
* @param nums The array of integers used to search the solution
* @param target The target that the quadruplet needs to sum
* @return A list with the unique quadruplets
*/
public List<List<Integer>> findSolution(int[] nums, int target) {
// Creates an empty list to store the result
List<List<Integer>> result = new ArrayList<>();

// If nums have less than 4 elements, returns null
if (nums == null || nums.length < 4) {
return result;
}

Arrays.sort(nums);

int numsLen = nums.length;

// Generates the quadruplets
for (int i = 0; i < numsLen; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicates
for (int j = i + 1; j < numsLen; j++) {
if (j > 1 && nums[j] == nums[j - 1]) continue; // Skip duplicates
for (int k = j + 1; k < numsLen; k++) {
if (k > 2 && nums[k] == nums[k - 1]) continue; // Skip duplicates
for (int l = k + 1; l < numsLen; l++) {
if (l > 3 && nums[l] == nums[l - 1]) continue; // Skip duplicates
// Verifies if the current quadruplet equals target
if (nums[i] + nums[j] + nums[k] + nums[l] == target) {
List<Integer> curr = new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));

// Sorts the current quadruplet
Collections.sort(curr);

// Check that the solution has not added before
if (!result.contains(curr)) {
result.add(curr);
}
}
}
}
}
}
return result;
}

}