diff --git a/src/main/java/com/thealgorithms/misc/FourSumProblemjava b/src/main/java/com/thealgorithms/misc/FourSumProblemjava new file mode 100644 index 000000000000..307b1537743c --- /dev/null +++ b/src/main/java/com/thealgorithms/misc/FourSumProblemjava @@ -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> findSolution(int[] nums, int target) { + // Creates an empty list to store the result + List> 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 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; + } + +}