Skip to content

Commit d63d3fb

Browse files
authored
Created a Add_4_Sum_Problem.java
1 parent e499d3b commit d63d3fb

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.util.*;
2+
3+
public class FourSum {
4+
public static List<List<Integer>> fourSum(int[] arr, int target) {
5+
List<List<Integer>> result = new ArrayList<>();
6+
if (arr == null || arr.length < 4) return result;
7+
8+
Arrays.sort(arr);
9+
int n = arr.length;
10+
11+
12+
for (int i = 0; i < n - 3; i++) {
13+
if (i > 0 && arr[i] == arr[i - 1]) continue; // Skip duplicates.
14+
15+
for (int j = i + 1; j < n - 2; j++) {
16+
if (j > i + 1 && arr[j] == arr[j - 1]) continue; // Skip duplicates.
17+
18+
int left = j + 1;
19+
int right = n - 1;
20+
21+
while (left < right) {
22+
int sum = arr[i] + arr[j] + arr[left] + arr[right];
23+
24+
if (sum == target) {
25+
result.add(Arrays.asList(arr[i], arr[j], arr[left], arr[right]));
26+
27+
28+
while (left < right && arr[left] == arr[left + 1]) left++;
29+
while (left < right && arr[right] == arr[right - 1]) right--;
30+
31+
left++;
32+
right--;
33+
} else if (sum < target) {
34+
left++;
35+
} else {
36+
right--;
37+
}
38+
}
39+
}
40+
}
41+
return result;
42+
}
43+
44+
public static void main(String[] args) {
45+
Scanner scanner = new Scanner(System.in);
46+
47+
System.out.print("Enter the number of elements in the array: ");
48+
int n = scanner.nextInt();
49+
int[] arr = new int[n];
50+
51+
System.out.println("Enter the elements of the array:");
52+
for (int i = 0; i < n; i++) {
53+
arr[i] = scanner.nextInt();
54+
}
55+
56+
System.out.print("Enter the target value: ");
57+
int target = scanner.nextInt();
58+
59+
List<List<Integer>> result = fourSum(arr, target);
60+
System.out.println("Unique quadruplets that sum to " + target + ":");
61+
for (List<Integer> quad : result) {
62+
System.out.println(quad);
63+
}
64+
65+
scanner.close();
66+
}
67+
}

0 commit comments

Comments
 (0)