|
| 1 | +--- |
| 2 | +id: 4Sum |
| 3 | +title: 4Sum (LeetCode) |
| 4 | +sidebar_label: 0018-4Sum |
| 5 | +tags: |
| 6 | + - Arrays |
| 7 | + - Hashing |
| 8 | + - Two Pointers |
| 9 | +description: Given an array `nums` of `n` integers, return an array of all the unique quadruplets `[nums[a], nums[b], nums[c], nums[d]]` such that: |
| 10 | + |
| 11 | +- `0 <= a, b, c, d < n` |
| 12 | +- `a, b, c, and d are distinct` |
| 13 | +- `nums[a] + nums[b] + nums[c] + nums[d] == target` |
| 14 | + |
| 15 | +--- |
| 16 | + |
| 17 | +## Problem Description |
| 18 | + |
| 19 | +| Problem Statement |
| 20 | +| Solution Link |
| 21 | +| LeetCode Profile |
| 22 | +| |
| 23 | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | |
| 24 | +| [4Sum](https://leetcode.com/problems/4Sum/) |
| 25 | +| [4Sum Solution on LeetCode](https://leetcode.com/problems/4Sum/solutions/5055810/video-two-pointer-solution/) |
| 26 | +| [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | |
| 27 | + |
| 28 | +### Problem Description |
| 29 | + |
| 30 | +## Problem Statement: |
| 31 | +Write a function that finds all unique quadruplets in the array which gives the sum of the target. |
| 32 | + |
| 33 | +### Examples |
| 34 | + |
| 35 | +#### Example 1 |
| 36 | + |
| 37 | +- **Input:** `nums = [1,0,-1,0,-2,2]` |
| 38 | + `target = 0` |
| 39 | +- **Output:** `[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]` |
| 40 | + |
| 41 | +#### Example 2 |
| 42 | + |
| 43 | +- **Input:** `nums = [2,2,2,2,2]` |
| 44 | + `target = 8` |
| 45 | +- **Output:** `[2,2,2,2]` |
| 46 | + |
| 47 | +## Constraints |
| 48 | +- `1 <= nums.length <= 200` |
| 49 | +- `-10^9 <= nums[i] <= 10^9` |
| 50 | +- `-10^9 <= target <= 10^9` |
| 51 | + |
| 52 | +## Approach |
| 53 | +1. **Sorting**: Start by sorting the array `nums`. This helps in avoiding duplicates and simplifies the two-pointer approach. |
| 54 | +2. **Nested Loops**: Use two nested loops to fix the first two elements of the quadruplet (`i` and `j`). The outer loop runs from `0` to `n-3` and the inner loop runs from `i+1` to `n-2`. |
| 55 | +3. **Two-Pointer Technique**: For the remaining two elements of the quadruplet, use two pointers (`left` and `right`). Initialize `left` to `j+1` and `right` to `n-1`. |
| 56 | +4. **Avoiding Duplicates**: Skip duplicate elements in both the outer and inner loops to ensure the uniqueness of quadruplets. |
| 57 | +5. **Finding Quadruplets**: Check if the sum of the current quadruplet equals the target. If it does, add it to the result list. Then, move the `left` and `right` pointers inward, skipping duplicates. |
| 58 | +6. **Adjusting Pointers**: If the sum is less than the target, move the `left` pointer to the right. If the sum is greater than the target, move the `right` pointer to the left. |
| 59 | +7. **Returning the Result**: Once all quadruplets are found, return the result list. |
| 60 | + |
| 61 | +### Solution Code |
| 62 | + |
| 63 | +#### Python |
| 64 | + |
| 65 | +```python |
| 66 | +class Solution: |
| 67 | + def fourSum(self, nums, target): |
| 68 | + nums.sort() |
| 69 | + n = len(nums) |
| 70 | + result = [] |
| 71 | + |
| 72 | + for i in range(n - 3): |
| 73 | + if i > 0 and nums[i] == nums[i - 1]: |
| 74 | + continue |
| 75 | + for j in range(i + 1, n - 2): |
| 76 | + if j > i + 1 and nums[j] == nums[j - 1]: |
| 77 | + continue |
| 78 | + |
| 79 | + left = j + 1 |
| 80 | + right = n - 1 |
| 81 | + |
| 82 | + while left < right: |
| 83 | + sum_ = nums[i] + nums[j] + nums[left] + nums[right] |
| 84 | + |
| 85 | + if sum_ == target: |
| 86 | + result.append([nums[i], nums[j], nums[left], nums[right]]) |
| 87 | + |
| 88 | + while left < right and nums[left] == nums[left + 1]: |
| 89 | + left += 1 |
| 90 | + while left < right and nums[right] == nums[right - 1]: |
| 91 | + right -= 1 |
| 92 | + |
| 93 | + left += 1 |
| 94 | + right -= 1 |
| 95 | + elif sum_ < target: |
| 96 | + left += 1 |
| 97 | + else: |
| 98 | + right -= 1 |
| 99 | + |
| 100 | + return result |
| 101 | +``` |
| 102 | + |
| 103 | +#### Java |
| 104 | + |
| 105 | +```java |
| 106 | +import java.util.ArrayList; |
| 107 | +import java.util.Arrays; |
| 108 | +import java.util.List; |
| 109 | + |
| 110 | +public class Solution { |
| 111 | + public List<List<Integer>> fourSum(int[] nums, int target) { |
| 112 | + List<List<Integer>> result = new ArrayList<>(); |
| 113 | + if (nums == null || nums.length < 4) { |
| 114 | + return result; |
| 115 | + } |
| 116 | + |
| 117 | + Arrays.sort(nums); |
| 118 | + int n = nums.length; |
| 119 | + |
| 120 | + for (int i = 0; i < n - 3; i++) { |
| 121 | + if (i > 0 && nums[i] == nums[i - 1]) { |
| 122 | + continue; |
| 123 | + } |
| 124 | + for (int j = i + 1; j < n - 2; j++) { |
| 125 | + if (j > i + 1 && nums[j] == nums[j - 1]) { |
| 126 | + continue; |
| 127 | + } |
| 128 | + |
| 129 | + int left = j + 1; |
| 130 | + int right = n - 1; |
| 131 | + |
| 132 | + while (left < right) { |
| 133 | + long sum = (long) nums[i] + nums[j] + nums[left] + nums[right]; |
| 134 | + |
| 135 | + if (sum == target) { |
| 136 | + result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right])); |
| 137 | + |
| 138 | + while (left < right && nums[left] == nums[left + 1]) { |
| 139 | + left++; |
| 140 | + } |
| 141 | + while (left < right && nums[right] == nums[right - 1]) { |
| 142 | + right--; |
| 143 | + } |
| 144 | + |
| 145 | + left++; |
| 146 | + right--; |
| 147 | + } else if (sum < target) { |
| 148 | + left++; |
| 149 | + } else { |
| 150 | + right--; |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + return result; |
| 157 | + } |
| 158 | + |
| 159 | + public static void main(String[] args) { |
| 160 | + Solution solution = new Solution(); |
| 161 | + |
| 162 | + int[] nums1 = {1, 0, -1, 0, -2, 2}; |
| 163 | + int target1 = 0; |
| 164 | + List<List<Integer>> result1 = solution.fourSum(nums1, target1); |
| 165 | + System.out.println(result1); |
| 166 | + |
| 167 | + int[] nums2 = {2, 2, 2, 2, 2}; |
| 168 | + int target2 = 8; |
| 169 | + List<List<Integer>> result2 = solution.fourSum(nums2, target2); |
| 170 | + System.out.println(result2); |
| 171 | + } |
| 172 | +} |
| 173 | +``` |
| 174 | + |
| 175 | +#### CPP: |
| 176 | +```cpp |
| 177 | +#include <vector> |
| 178 | +#include <algorithm> |
| 179 | + |
| 180 | +class Solution { |
| 181 | +public: |
| 182 | + std::vector<std::vector<int>> fourSum(std::vector<int>& nums, int target) { |
| 183 | + std::vector<std::vector<int>> result; |
| 184 | + if (nums.size() < 4) return result; |
| 185 | + |
| 186 | + std::sort(nums.begin(), nums.end()); |
| 187 | + int n = nums.size(); |
| 188 | + |
| 189 | + for (int i = 0; i < n - 3; ++i) { |
| 190 | + if (i > 0 && nums[i] == nums[i - 1]) continue; |
| 191 | + for (int j = i + 1; j < n - 2; ++j) { |
| 192 | + if (j > i + 1 && nums[j] == nums[j - 1]) continue; |
| 193 | + |
| 194 | + int left = j + 1; |
| 195 | + int right = n - 1; |
| 196 | + |
| 197 | + while (left < right) { |
| 198 | + long sum = (long)nums[i] + nums[j] + nums[left] + nums[right]; |
| 199 | + |
| 200 | + if (sum == target) { |
| 201 | + result.push_back({nums[i], nums[j], nums[left], nums[right]}); |
| 202 | + |
| 203 | + while (left < right && nums[left] == nums[left + 1]) ++left; |
| 204 | + while (left < right && nums[right] == nums[right - 1]) --right; |
| 205 | + |
| 206 | + ++left; |
| 207 | + --right; |
| 208 | + } else if (sum < target) { |
| 209 | + ++left; |
| 210 | + } else { |
| 211 | + --right; |
| 212 | + } |
| 213 | + } |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + return result; |
| 218 | + } |
| 219 | +}; |
| 220 | +``` |
| 221 | + |
| 222 | +#### JavaScript |
| 223 | +```js |
| 224 | +/** |
| 225 | + * @param {number[]} nums |
| 226 | + * @param {number} target |
| 227 | + * @return {number[][]} |
| 228 | + */ |
| 229 | +var fourSum = function(nums, target) { |
| 230 | + let result = []; |
| 231 | + if (nums.length < 4) return result; |
| 232 | + |
| 233 | + nums.sort((a, b) => a - b); |
| 234 | + |
| 235 | + for (let i = 0; i < nums.length - 3; i++) { |
| 236 | + if (i > 0 && nums[i] === nums[i - 1]) continue; |
| 237 | + for (let j = i + 1; j < nums.length - 2; j++) { |
| 238 | + if (j > i + 1 && nums[j] === nums[j - 1]) continue; |
| 239 | + |
| 240 | + let left = j + 1; |
| 241 | + let right = nums.length - 1; |
| 242 | + |
| 243 | + while (left < right) { |
| 244 | + let sum = nums[i] + nums[j] + nums[left] + nums[right]; |
| 245 | + |
| 246 | + if (sum === target) { |
| 247 | + result.push([nums[i], nums[j], nums[left], nums[right]]); |
| 248 | + while (left < right && nums[left] === nums[left + 1]) left++; |
| 249 | + while (left < right && nums[right] === nums[right - 1]) right--; |
| 250 | + left++; |
| 251 | + right--; |
| 252 | + } else if (sum < target) { |
| 253 | + left++; |
| 254 | + } else { |
| 255 | + right--; |
| 256 | + } |
| 257 | + } |
| 258 | + } |
| 259 | + } |
| 260 | + |
| 261 | + return result; |
| 262 | +}; |
| 263 | + |
| 264 | +// Example Usage |
| 265 | +console.log(fourSum([1,0,-1,0,-2,2], 0)); |
| 266 | +console.log(fourSum([2,2,2,2,2], 8)); |
| 267 | +``` |
| 268 | + |
| 269 | +## Step-by-Step Algorithm |
| 270 | + |
| 271 | +1. **Input Validation**: Check if the array is null or has fewer than 4 elements. If so, return an empty list. |
| 272 | +2. **Sort the Array**: Sort the input array `nums`. |
| 273 | +3. **Outer Loop**: Iterate over the array with index `i` from `0` to `n-4`. |
| 274 | + - Skip duplicate elements by checking if `nums[i] == nums[i-1]` (for `i > 0`). |
| 275 | +4. **Inner Loop**: For each `i`, iterate with index `j` from `i+1` to `n-3`. |
| 276 | + - Skip duplicate elements by checking if `nums[j] == nums[j-1]` (for `j > i+1`). |
| 277 | +5. **Two Pointers**: Initialize two pointers `left = j+1` and `right = n-1`. |
| 278 | +6. **Finding Quadruplets**: |
| 279 | + - While `left < right`: |
| 280 | + - Calculate the sum of the quadruplet: `sum = nums[i] + nums[j] + nums[left] + nums[right]`. |
| 281 | + - If the sum equals the target: |
| 282 | + - Add `[nums[i], nums[j], nums[left], nums[right]]` to the result. |
| 283 | + - Move `left` to the right, skipping duplicates. |
| 284 | + - Move `right` to the left, skipping duplicates. |
| 285 | + - If the sum is less than the target, move `left` to the right. |
| 286 | + - If the sum is greater than the target, move `right` to the left. |
| 287 | +7. **Return the Result**: After processing all elements, return the list of quadruplets. |
0 commit comments