sagelearnai

4Sum

Difficulty: Medium · Pattern: Two Pointers · LeetCode #18

Return all unique quadruplets [a, b, c, d] of values from distinct indices with a + b + c + d == target, in any order.

Examples

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

Hints

  1. Generalize 3Sum: fix two indices, then two-pointer the rest.
  2. Sort, and skip equal values at each fixed level to avoid duplicates.

Approach

Sort. Loop i, then j > i (skipping duplicate values at each level), then run two pointers l, r on the remainder looking for target − nums[i] − nums[j]. On a hit, record it and skip duplicates for l and r. O(n³) time, which is the best known bound for k = 4 without extra memory tricks.

Complexity

Time: O(n³). Space: O(1) extra (excluding output).

Python solution
def fourSum(nums, target):
    nums.sort()
    n, res = len(nums), []
    for i in range(n - 3):
        if i 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
            l, r = j + 1, n - 1
            while l < r:
                s = nums[i] + nums[j] + nums[l] + nums[r]
                if s < target:
                    l += 1
                elif s > target:
                    r -= 1
                else:
                    res.append([nums[i], nums[j], nums[l], nums[r]])
                    l += 1; r -= 1
                    while l < r and nums[l] == nums[l - 1]: l += 1
                    while l < r and nums[r] == nums[r + 1]: r -= 1
    return res
JavaScript solution
function fourSum(nums, target) {
  nums.sort((a, b) => a - b);
  const n = nums.length, res = [];
  for (let i = 0; i < n - 3; i++) {
    if (i && 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 l = j + 1, r = n - 1;
      while (l < r) {
        const s = nums[i] + nums[j] + nums[l] + nums[r];
        if (s < target) l++;
        else if (s > target) r--;
        else {
          res.push([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--;
        }
      }
    }
  }
  return res;
}