Skip to content

Commit 7aa6886

Browse files
author
volimroze
committed
Add 4-Sum Problem implementation
1 parent c301fec commit 7aa6886

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.thealgorithms.misc;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class FourSumProblem {
8+
9+
public static List<List<Integer>> fourSum(int[] nums, int target) {
10+
List<List<Integer>> result = new ArrayList<>();
11+
12+
if (nums == null || nums.length < 4) {
13+
return result; // if array is too small to have 4 numbers, return empty result
14+
}
15+
16+
// Sort the array first
17+
Arrays.sort(nums);
18+
19+
// Iterate through the array, fixing the first two elements
20+
for (int i = 0; i < nums.length - 3; i++) {
21+
if (i > 0 && nums[i] == nums[i - 1]) continue; // Skip duplicates for the first element
22+
23+
for (int j = i + 1; j < nums.length - 2; j++) {
24+
if (j > i + 1 && nums[j] == nums[j - 1]) continue; // Skip duplicates for the second element
25+
26+
// Use two pointers for the remaining two elements
27+
int left = j + 1;
28+
int right = nums.length - 1;
29+
30+
while (left < right) {
31+
int sum = nums[i] + nums[j] + nums[left] + nums[right];
32+
33+
if (sum == target) {
34+
// If we found a quadruplet, add it to the result list
35+
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
36+
37+
// Skip duplicates for the third element
38+
while (left < right && nums[left] == nums[left + 1]) left++;
39+
// Skip duplicates for the fourth element
40+
while (left < right && nums[right] == nums[right - 1]) right--;
41+
42+
// Move the pointers
43+
left++;
44+
right--;
45+
} else if (sum < target) {
46+
// If the sum is less than the target, move the left pointer to increase the sum
47+
left++;
48+
} else {
49+
// If the sum is greater than the target, move the right pointer to decrease the sum
50+
right--;
51+
}
52+
}
53+
}
54+
}
55+
56+
return result;
57+
}
58+
}

0 commit comments

Comments
 (0)