Skip to problem
←

4Sum

Medium 0 attempts

Given an integer array nums and an integer target, return all unique groups of four values whose sum equals target. Each group must use four distinct indices in nums.

Return the values, not their indices. Do not include duplicate groups, even when different choices of indices produce the same values.

Function contract

Implement fourSum(nums, target), where nums is an integer array and target is an integer.

Output: An array of unique value quadruplets summing to target. Use four distinct indices. Quadruplet order and value order do not matter.

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]]

Example 2

Input
nums = [2,2,2,2,2]
target = 8
Output
[[2,2,2,2]]
Constraints
  • 1 <= nums.length <= 200
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9

Sort the array. Use two nested loops to fix the first two numbers, then use two pointers to find the remaining two. Skip duplicates at every level to avoid duplicate quadruplets.

javascript
function fourSum(nums, target) {
  nums.sort((a, b) => a - b);
  const result = [];
  const n = nums.length;

  for (let i = 0; i < n - 3; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) continue;
    for (let j = i + 1; j < n - 2; j++) {
      if (j > i + 1 && nums[j] === nums[j - 1]) continue;
      let left = j + 1, right = n - 1;
      while (left < right) {
        const sum = nums[i] + nums[j] + nums[left] + nums[right];
        if (sum === target) {
          result.push([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 < target) left++;
        else right--;
      }
    }
  }

  return result;
}

Time: O(n³) Space: O(1) for the pointer scan, excluding the output and the JavaScript engine’s sorting workspace. The sort may allocate additional memory.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript