4Sum

medium

Given an integer array nums and an integer target, find all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] — where a, b, c, and d are four different indices — whose values add up to target.

Two quadruplets count as the same if they hold the same four values, so your answer must not contain any quadruplet twice. The order of the quadruplets, and the order of the numbers inside each one, does not matter.

Hints

You're looking for four numbers that hit target. What if you nailed some of them down first and searched only for the rest?
Fix two numbers a and b; the remaining pair must sum to target - a - b — that's Two Sum all over again.
Sort the array, fix two anchors with an outer double loop, then two-pointer the remaining pair inward. Skip equal anchor and pointer values to keep quadruplets unique.

Common doubts

Sorting lets you skip duplicate values in O(1) and enables the two-pointer squeeze. It also emits each quadruplet in a canonical order, so deduplication is trivial.
Skip an anchor when it equals the previous one, and after recording a match advance both pointers past any repeated values. Each distinct quadruplet is then emitted exactly once.
Yes — with values up to 10^9, a sum can reach 4 * 10^9, which overflows a 32-bit int. In C++ accumulate into a long long; Go and Python ints are wide enough already.

Interview follow-ups

Recurse: fix one anchor to reduce kSum to (k-1)Sum, and bottom out at 2Sum solved with two pointers. 4Sum is just two anchor loops wrapped around that base case.
O(n^(k-1)) — each fixed anchor adds a factor of n, and the innermost 2Sum is linear after the one-time sort.
You can hash all pair sums for roughly O(n^2) average time, but deduplicating overlapping index pairs is fiddly; the sorted two-pointer solution is the standard interview answer.

Fun facts

  • 4Sum is the k=4 rung of the kSum ladder — the same fix-an-anchor-and-recurse trick solves 2Sum, 3Sum, 4Sum, and beyond.
  • The two-pointer squeeze here is the exact same move used in 3Sum, Container With Most Water, and Trapping Rain Water.

Asked at

AmazonGoogleMicrosoftAdobeApple
Frequently Sometimes Occasionally
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]]
Three distinct quadruplets sum to 0: (-2)+(-1)+1+2, (-2)+0+0+2, and (-1)+0+0+1. Order does not matter.
Example 2
Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]
Any four of the five 2s sum to 8, but they all form the same value-quadruplet [2,2,2,2], so it appears only once.
Constraints

- 1 <= nums.length <= 200 - -10^9 <= nums[i] <= 10^9 - -10^9 <= target <= 10^9

Solve this problem →