Skip to content

Created a Add_4_Sum_Problem.java #5931

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
67 changes: 67 additions & 0 deletions src/test/java/com/thealgorithms/misc/Add_4_Sum_Problem.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.*;

public class FourSum {
public static List<List<Integer>> fourSum(int[] arr, int target) {
List<List<Integer>> result = new ArrayList<>();
if (arr == null || arr.length < 4) return result;

Arrays.sort(arr);
int n = arr.length;


for (int i = 0; i < n - 3; i++) {
if (i > 0 && arr[i] == arr[i - 1]) continue; // Skip duplicates.

for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && arr[j] == arr[j - 1]) continue; // Skip duplicates.

int left = j + 1;
int right = n - 1;

while (left < right) {
int sum = arr[i] + arr[j] + arr[left] + arr[right];

if (sum == target) {
result.add(Arrays.asList(arr[i], arr[j], arr[left], arr[right]));


while (left < right && arr[left] == arr[left + 1]) left++;
while (left < right && arr[right] == arr[right - 1]) right--;

left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return result;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter the target value: ");
int target = scanner.nextInt();

List<List<Integer>> result = fourSum(arr, target);
System.out.println("Unique quadruplets that sum to " + target + ":");
for (List<Integer> quad : result) {
System.out.println(quad);
}

scanner.close();
}
}
Loading