4Sum
Problem 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:
0 <= a, b, c, d < na,b,c, anddare distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Examples
Example 1:Input: nums = [1,0,-1,0,-2,2], target = 0 Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Input: nums = [2,2,2,2,2], target = 8 Output: [[2,2,2,2]]
Constraints
1 <= nums.length <= 200-10⁹ <= nums[i] <= 10⁹-10⁹ <= target <= 10⁹
Reducing K-Sum to Two Pointers
Like 3Sum, we can reduce 4Sum to a two-pointer problem by sorting the array and using nested loops. Two outer loops fix the first two numbers, and a two-pointer approach finds the remaining two numbers. To prevent duplicate quadruplets, we skip duplicate values at each step. This reduces the time complexity from a naive O(n⁴) to O(n³).
Solution 1: Nested Loops with Two Pointers
Sort the array and run two outer loops, using two pointers for the inner search.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length < 4) return result;
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // skip duplicates
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue; // skip duplicates
long newTarget = (long) target - nums[i] - nums[j];
int left = j + 1, right = n - 1;
while (left < right) {
long sum = nums[left] + nums[right];
if (sum == newTarget) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < newTarget) {
left++;
} else {
right--;
}
}
}
}
return result;
}
}class Solution:
def fourSum(self, nums: list[int], target: int) -> list[list[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
new_target = target - nums[i] - nums[j]
left, right = j + 1, n - 1
while left < right:
curr_sum = nums[left] + nums[right]
if curr_sum == new_target:
result.append([nums[i], nums[j], nums[left], nums[right]])
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
elif curr_sum < new_target:
left += 1
else:
right -= 1
return result#include <vector>
#include <algorithm>
class Solution {
public:
std::vector<std::vector<int>> fourSum(std::vector<int>& nums, int target) {
std::vector<std::vector<int>> result;
if (nums.size() < 4) return result;
std::sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
long long newTarget = (long long)target - nums[i] - nums[j];
int left = j + 1, right = n - 1;
while (left < right) {
long long sum = nums[left] + nums[right];
if (sum == newTarget) {
result.push_back({nums[i], nums[j], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < newTarget) {
left++;
} else {
right--;
}
}
}
}
return result;
}
};Complexity Analysis
- Time Complexity: O(n³) as sorting takes O(n log n) and the nested loops run three levels deep.
- Space Complexity: O(log n) to O(n) depending on the sorting implementation.
Where It Breaks
If the inputs are very large (e.g. n > 1000), the cubic time complexity becomes too slow. For larger lists of numbers, k-sum requires hash-based approaches or other indexing strategies.
Common Mistakes
- Integer Overflow: Not casting the target subtraction to a 64-bit integer (
longin Java/C++). Sums of large numbers like10^9can overflow 32-bit registers. - Duplicate Checks: Forgetting to skip duplicates on
jor not resetting pointer checks correctly inside the loop.
Frequently Asked Questions
Can this be generalized to K-sum? Yes. You can write a recursive function that reduces the K-sum problem to K-1 sum, terminating when it reaches Two Sum (the two-pointer base case).
What happens if n < 4?
The solution returns an empty list immediately, satisfying the initial boundary constraints.