|
| 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 | + for (int i = 0; i < n - 3; i++) { |
| 12 | + if (i > 0 && arr[i] == arr[i - 1]) continue; // Skip duplicates. |
| 13 | + |
| 14 | + for (int j = i + 1; j < n - 2; j++) { |
| 15 | + if (j > i + 1 && arr[j] == arr[j - 1]) continue; // Skip duplicates. |
| 16 | + |
| 17 | + int left = j + 1; |
| 18 | + int right = n - 1; |
| 19 | + |
| 20 | + while (left < right) { |
| 21 | + int sum = arr[i] + arr[j] + arr[left] + arr[right]; |
| 22 | + |
| 23 | + if (sum == target) { |
| 24 | + result.add(Arrays.asList(arr[i], arr[j], arr[left], arr[right])); |
| 25 | + |
| 26 | + while (left < right && arr[left] == arr[left + 1]) left++; |
| 27 | + while (left < right && arr[right] == arr[right - 1]) right--; |
| 28 | + |
| 29 | + left++; |
| 30 | + right--; |
| 31 | + } else if (sum < target) { |
| 32 | + left++; |
| 33 | + } else { |
| 34 | + right--; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + Scanner scanner = new Scanner(System.in); |
| 44 | + |
| 45 | + |
| 46 | + System.out.print("Enter the number of elements in the array: "); |
| 47 | + int n = scanner.nextInt(); |
| 48 | + int[] arr = new int[n]; |
| 49 | + |
| 50 | + System.out.println("Enter the elements of the array:"); |
| 51 | + for (int i = 0; i < n; i++) { |
| 52 | + arr[i] = scanner.nextInt(); |
| 53 | + } |
| 54 | + |
| 55 | + System.out.print("Enter the target value: "); |
| 56 | + int target = scanner.nextInt(); |
| 57 | + |
| 58 | + List<List<Integer>> result = fourSum(arr, target); |
| 59 | + System.out.println("Unique quadruplets that sum to " + target + ":"); |
| 60 | + for (List<Integer> quad : result) { |
| 61 | + System.out.println(quad); |
| 62 | + } |
| 63 | + |
| 64 | + scanner.close(); |
| 65 | + } |
| 66 | +} |
0 commit comments