4Sum

Two nested anchors plus two-pointer inner scan — sort first, skip duplicates at all four levels.

Medium
Time O(n^3) Space O(1)
LeetCode
5 min read
two-pointers array sorting

Problem#

Return all unique quadruples in nums that sum to target.

Examples#

  • nums=[1,0,-1,0,-2,2], target=0[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]].
  • nums=[2,2,2,2,2], target=8[[2,2,2,2]].

Constraints#

  • 1 <= nums.length <= 200.

Approach#

Sort. Two outer loops fix the first two values, then two-pointer the rest. Skip duplicates at every level. Use long long for the sum to avoid overflow.

Solution#

4Sum
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> ans;
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;
long long need = (long long)target - nums[i] - nums[j];
int l = j + 1, r = n - 1;
while (l < r) {
long long s = (long long)nums[l] + nums[r];
if (s == need) {
ans.push_back({nums[i], nums[j], nums[l], nums[r]});
++l; --r;
while (l < r && nums[l] == nums[l-1]) ++l;
while (l < r && nums[r] == nums[r+1]) --r;
} else if (s < need) ++l;
else --r;
}
}
}
return ans;
}
};

Editorial#

The classic K-Sum trick: anchor K - 2 indices with nested loops, then two-pointer for the remaining two. Duplicate skipping at all four levels is essential — overlooking one produces duplicate quadruples in the output.

Complexity#

  • Time: O(n^3).
  • Space: O(1) ignoring output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.