https://github.com/emahtab/four-sum
Four Sum
https://github.com/emahtab/four-sum
leetcode problem-solving
Last synced: 3 months ago
JSON representation
Four Sum
- Host: GitHub
- URL: https://github.com/emahtab/four-sum
- Owner: eMahtab
- Created: 2020-01-09T18:07:45.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-01-09T18:34:21.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:25:29.774Z (5 months ago)
- Topics: leetcode, problem-solving
- Size: 5.86 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Four Sum
## https://leetcode.com/problems/4sumGiven an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
**Note: The solution set must not contain duplicate quadruplets.**
```
Example:Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
```## Implementation :
```java
public static List> fourSum(int[] nums, int target) {
List> result = new ArrayList>();
if(nums == null || nums.length < 4)
return result;
int n = nums.length;
for(int i = 0; i < n - 3; i++) {
for(int j = i + 1; j < n - 2; j++) {
for(int k = j + 1; k < n - 1; k++) {
for(int l = k + 1; l < n; l++) {
if((nums[i] + nums[j] + nums[k] + nums[l]) == target ) {
addResult(result, new Integer[] {nums[i], nums[j], nums[k], nums[l]});
break;
}
}
}
}
}
return result;
}private static void addResult(List> result, Integer[] quadruplet) {
Set fourSum = new HashSet(Arrays.asList(quadruplet));
boolean alredayExists = false;
for(List list: result) {
Set res = new HashSet(list);
if(res.equals(fourSum)) {
alredayExists = true;
break;
}
}
if(!alredayExists) {
result.add(Arrays.asList(quadruplet));
}
}
```The runtime complexity of above implementation is O(n^4) and space complexity is O(1)
```
Runtime Complexity = O(n^4)
Space Complexity = O(1)
```