Skip to content

Commit d29a467

Browse files
committed
Added 4-Sum Problem implementation
1 parent e499d3b commit d29a467

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.List;
4+
5+
public class fourSum {
6+
public static List<List<Integer>> fourSum(int[] nums, int target) {
7+
List<List<Integer>> result = new ArrayList<>();
8+
if (nums == null || nums.length < 4)
9+
return result;
10+
11+
Arrays.sort(nums); // Sort the array first
12+
13+
for (int i = 0; i < nums.length - 3; i++) {
14+
if (i > 0 && nums[i] == nums[i - 1])
15+
continue; // Skip duplicates
16+
for (int j = i + 1; j < nums.length - 2; j++) {
17+
if (j > i + 1 && nums[j] == nums[j - 1])
18+
continue; // Skip duplicates
19+
int left = j + 1, right = nums.length - 1;
20+
while (left < right) {
21+
int sum = nums[i] + nums[j] + nums[left] + nums[right];
22+
if (sum == target) {
23+
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
24+
while (left < right && nums[left] == nums[left + 1])
25+
left++; // Skip duplicates
26+
while (left < right && nums[right] == nums[right - 1])
27+
right--; // Skip duplicates
28+
left++;
29+
right--;
30+
} else if (sum < target) {
31+
left++;
32+
} else {
33+
right--;
34+
}
35+
}
36+
}
37+
}
38+
return result;
39+
}
40+
41+
public static void main(String[] args) {
42+
int[] arr1 = { 1, 0, -1, 0, -2, 2 };
43+
int target1 = 0;
44+
System.out.println(fourSum(arr1, target1));
45+
46+
int[] arr2 = { 4, 3, 3, 4, 4, 2, 1, 2, 1, 1 };
47+
int target2 = 9;
48+
System.out.println(fourSum(arr2, target2));
49+
}
50+
}

0 commit comments

Comments
 (0)