Skip to content
thesarfo

Reference

Four Sum

Finding all unique quadruplets summing to a target — nested loops, hashing to drop a loop, then sort + two pointers extending the Three Sum pattern.

views 0

Find all unique quadruplets summing to target. [1,0,-1,0,-2,2], target=0 → all unique 4-element combinations summing to zero. (LeetCode 18)

Brute force: four nested loops generating every quad, deduped via a set — O(n⁴).

Better — hashing to drop the innermost loop: fix i, j, k; the fourth value is deducible as target - (nums[i]+nums[j]+nums[k]), looked up in a hash set built as k advances — O(n³ log m).

Optimal — sort + two pointers, extending the Three Sum pattern: fix i and j, then close k/l inward, skipping duplicates at every one of the four pointer positions.

public class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
int n = nums.length;
for (int i = 0; i < n; i++) {
if (i != 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) continue;
int k = j + 1;
int l = n - 1;
while (k < l) {
long sum = (long) nums[i] + nums[j] + nums[k] + nums[l];
if (sum == target) {
ans.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
k++;
l--;
while (k < l && nums[k] == nums[k - 1]) k++;
while (k < l && nums[l] == nums[l + 1]) l--;
} else if (sum < target) {
k++;
} else {
l--;
}
}
}
}
return ans;
}
}

Time: O(n³). Space: O(number of quadruplets).