Skip to content

Commit 9a1f387

Browse files
Merge pull request matthewsamuel95#260 from arpitpandey0209/master
Added Java solution for 4-Sum problem in O(n^2Logn). Issue matthewsamuel95#256
2 parents 8a0e249 + ae63736 commit 9a1f387

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Hashing/4_Sum/FourSum.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.util.*;
2+
3+
public class FourSum {
4+
5+
static class Pair {
6+
int first, second;
7+
Pair(int first, int second) {
8+
this.first = first;
9+
this.second = second;
10+
}
11+
}
12+
13+
/*
14+
* Returns a list containing 4 numbers present at different indexes which sum to target. If there are multiple solutions,
15+
* return any solution.
16+
* If there is no solution, return an empty list.
17+
*/
18+
static List<Integer> findSubset(int[] nums, int target) {
19+
List<Integer> result = new ArrayList<>();
20+
21+
// For every pair of elements, store their sum
22+
Map<Integer, Pair> map = new HashMap<>();
23+
24+
int n = nums.length;
25+
for (int i=0; i<n; i++) {
26+
for (int j=i+1; j<n; j++) {
27+
map.put(nums[i]+nums[j], new Pair(i, j));
28+
}
29+
}
30+
31+
for (int i=0; i<n; i++) {
32+
for (int j=i+1; j<n; j++) {
33+
int remainingSum = target - (nums[i] + nums[j]);
34+
if (map.containsKey(remainingSum)) {
35+
Pair pair = map.get(remainingSum);
36+
if (pair.first != i && pair.first != j && pair.second != i && pair.second != j) {
37+
result.addAll(Arrays.asList(nums[i], nums[j], nums[pair.first], nums[pair.second]));
38+
return result;
39+
}
40+
}
41+
}
42+
}
43+
return new ArrayList<Integer>();
44+
}
45+
46+
public static void main(String[] args) {
47+
int target = 23;
48+
int[] nums = {10, 2, 3, 4, 5, 9, 7, 8};
49+
List<Integer> result = findSubset(nums, target);
50+
if (result.size() != 4) {
51+
System.out.println("Four elements with the given sum not found in the array!");
52+
} else {
53+
for (int num : result) {
54+
System.out.print(num + " ");
55+
}
56+
System.out.println();
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)