15% off all plans & roadmaps Use code

See plans

4Sum

Updated

TL;DR: Sort the array, then try every pair of starting indices (i, j) and scan the rest of the array with converging two pointers. The sorted order lets each scan discard one candidate per step, which brings the work from O(n^4) down to O(n^3).

Problem

You are given an integer array nums of length n. Return every unique quadruplet [nums[a], nums[b], nums[c], nums[d]] that meets all three rules below.

  • 0 <= a, b, c, d < n
  • a, b, c, and d are distinct indices.
  • nums[a] + nums[b] + nums[c] + nums[d] == target

You may return the answer in any order.

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

Constraints that matter

  • n up to 200 means a plain scan of all index quadruples does about 6.5 * 10^7 checks, which is C(200, 4). Fixing two indices and scanning the rest with pointers does about 4 * 10^6 steps, so a cubic method fits easily.
  • Values up to 10^9 in size mean one sum can reach 4 * 10^9, which overflows a 32-bit int. The sum needs a 64-bit type in Java, C++ and C#.
  • Answers must be unique by value, not by index. Sorting puts equal values next to each other, so skipping a repeat costs one comparison.
  • n can be 1, so the code must handle arrays with fewer than four values and return an empty list.

View on LeetCode

Hints

Hint 1

The answer is a set of value combinations, not index combinations, so duplicates are the main trap.

Hint 2

The naive solution checks every set of four distinct indices.

Solution

Intuition

The answer is a set of value combinations, not index combinations, so duplicates are the main trap. Sorting handles that. Equal values end up next to each other, so one comparison tells you to skip a repeat.

Picture a sorted row of price tags with one hand at each end. Each move drops one tag the total cannot use, and the hands close in until they meet.

This problem uses the two pointers pattern in its converging form, applied in a chain. Fixing one value turns 4Sum into 3Sum. Fixing a second value turns it into 2Sum, and 2Sum on a sorted range is solved by a left pointer and a right pointer that close in from both ends.

The sum tells you which pointer to move. If the sum is below the target, the left value is too small even when paired with the largest remaining value, so you can discard it. If the sum is above the target, the right value is too large even with the smallest remaining left value. Each move throws away one candidate that cannot be part of an answer.

Watch the pattern animation

Worked example

Input: nums = [2, 2, 2, 2, 2], target = 8
Output: [[2,2,2,2]]
Explanation: Every value is 2, so any four of the five positions sum to 8. All five index choices produce the same quadruplet, so the answer keeps a single copy.

Approach 1: Brute force

The naive solution checks every set of four distinct indices. For each set that sums to the target, it sorts the four values and stores them in a set. The set collapses repeated answers into one entry.

The work depends only on the number of index sets, not on the values. The loops never use the sorted order, so this approach is correct but slow.

Steps

  1. Create an empty set to hold the answers.
  2. Loop over indices a < b < c < d so no index repeats.
  3. Compute the sum of the four values at those indices.
  4. If the sum equals target, sort the four values and add them to the set.
  5. Convert the set into a list and return it.

Dry run

On [2, 2, 2, 2, 2] with target 8 there are C(5, 4) = 5 index sets: (0,1,2,3), (0,1,2,4), (0,1,3,4), (0,2,3,4) and (1,2,3,4). Each set sums to 8, and each sorted tuple is (2, 2, 2, 2). The set keeps the first tuple and ignores the other four. The output is [[2,2,2,2]], which matches the example.

Complexity

TimeO(n^4)
SpaceO(u), where u is the number of unique quadruplets

Here n is the array length. Four nested loops with a < b < c < d run C(n, 4) times, which is about n^4 / 24, so the time is O(n^4). Each sum and each sort of four values takes constant work. The set holds one entry per unique answer, so the extra space is O(u).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        found = set()
        for a in range(n):
            for b in range(a + 1, n):
                for c in range(b + 1, n):
                    for d in range(c + 1, n):
                        if nums[a] + nums[b] + nums[c] + nums[d] == target:
                            # Sorting the four values makes the key independent of index order.
                            found.add(tuple(sorted((nums[a], nums[b], nums[c], nums[d]))))
        # Sort the unique quadruplets so the output order is deterministic.
        return [list(quad) for quad in sorted(found)]

The Converging (Sorted Array Target Sum) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Converging (Sorted Array Target Sum)

Part of Two Pointers

Approach 2: Sort, fix two, then converging two pointersOptimalConverging (Sorted Array Target Sum)

What's slow: the brute force checks each index set on its own, so it repeats the same pair sums over and over. Four nested loops cost n^4 work, and every match pays for a sort.

The insight that fixes it: after sorting, fix the first two indices and treat the last two as a 2Sum problem on the sorted tail. Converging pointers solve that in one linear scan, so the last two loops collapse into one pass.

Duplicates are handled by value. Skip a first or second index whose value repeats the one before it. After a match, skip every copy of the pointer values before moving on.

Why it is correct. The range between left and right always holds every candidate that could still complete the quadruplet for the fixed first two values. If the sum is below target, nums[left] paired with any value up to right is at most the current sum, so it can be dropped. The same argument drops right when the sum is above target, and skipping repeated values only skips identical value sets already tried.

Steps

  1. Sort nums in ascending order. Return an empty list if n is less than 4.
  2. For each start index i, skip it if nums[i] equals nums[i - 1].
  3. For each j after i, skip it if j > i + 1 and nums[j] equals nums[j - 1].
  4. Set left to j + 1 and right to n - 1. Compute the sum of the four values.
  5. If the sum equals target, record the quadruplet, then move left and right past every copy of their current values.
  6. If the sum is below target, move left one step right. If it is above target, move right one step left.
  7. Return the recorded quadruplets.

Dry run

Start with the sorted array [2, 2, 2, 2, 2] and target 8. The table tracks every change in order.

StepijleftrightsumActionAnswers
101248sum equals target, record it[[2,2,2,2]]
20144n/askip equal values, left stops at right[[2,2,2,2]]
30144n/aleft is not less than right, scan ends[[2,2,2,2]]
402n/an/an/anums[2] equals nums[1] and 2 > 0 + 1, skip[[2,2,2,2]]
51n/an/an/an/anums[1] equals nums[0], skip[[2,2,2,2]]
6n/an/an/an/an/aloops end, return the list[[2,2,2,2]]

The output is [[2,2,2,2]], which matches the example.

Complexity

TimeO(n^3)
SpaceO(1) extra, apart from the output and the sort's own memory

Here n is the array length. Sorting costs O(n log n), which the rest of the work absorbs. The pair loops visit at most about n^2 / 2 pairs (i, j). Each pointer scan moves at most n times, because the gap between left and right shrinks on every step. That gives O(n^2) * O(n) = O(n^3). The extra memory is a few integers, so the space is O(1) beyond the output.

PythonTested in our runner

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        n = len(nums)
        result = []
        if n < 4:
            return result
        for i in range(n - 3):
            # Skip a first index whose value was already used.
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            for j in range(i + 1, n - 2):
                # Skip a repeated second value, but never the first j after i.
                if j > i + 1 and nums[j] == nums[j - 1]:
                    continue
                left, right = j + 1, n - 1
                while left < right:
                    total = nums[i] + nums[j] + nums[left] + nums[right]
                    if total == target:
                        result.append([nums[i], nums[j], nums[left], nums[right]])
                        left_val, right_val = nums[left], nums[right]
                        # Skip every copy of both pointer values.
                        while left < right and nums[left] == left_val:
                            left += 1
                        while left < right and nums[right] == right_val:
                            right -= 1
                    elif total < target:
                        left += 1
                    else:
                        right -= 1
        return result

Common mistakes

  • if nums[j] == nums[j - 1] without the j > i + 1 guard: on [2,2,2,2,2] with target 8 this skips j = 1 and loses [2,2,2,2]. Add the guard so the first j after i is never skipped.
  • int total = nums[i] + nums[j] + nums[left] + nums[right] in Java, C++ or C#: values near 10^9 wrap around. Store the sum in a 64-bit type.
  • Recording a match without moving left and right: the pointers stay put and the same match repeats forever. Move both inward right after you record a quadruplet.
  • Moving left one step after a match without skipping copies: an input with two zeros can record [-1,0,0,1] twice. Skip every copy of nums[left] and nums[right] before the next check.
  • Starting the pointers at left = j instead of j + 1: the same index is used twice, which breaks the distinct-index rule and can build a quadruplet from only three numbers.

Edge cases

  • n = 3, such as [1, 1, 1] with target 3: fewer than four values means no quadruplet, so return an empty list.
  • All equal values, [2,2,2,2,2] with target 8: return [[2,2,2,2]] once. With target 7 return an empty list.
  • Large values, [-1000000000, -1000000000, 1000000000, 1000000000] with target 0: the sum is 0, so return that one quadruplet. The sum must not overflow.
  • Mixed signs with repeated zeros, [1,0,-1,0,-2,2] with target 0: return the three unique quadruplets, with [-1,0,0,1] appearing once even though 0 occurs twice.
  • Repeated values used up to their count, [1,1,1,1,2,2] with target 6: return [[1,1,2,2]] once, even though there are four 1s and two 2s.
  • Unreachable target, [1,2,3,4] with target 100: no sum matches, so return an empty list.

Follow-ups interviewers ask

What if you need k-Sum for any k?
Fix one value, then solve (k-1)-Sum on the rest of the sorted array, skipping duplicates at each level. The base case is 2Sum with converging pointers, which takes O(n) on sorted input. The total is O(n^(k-1)) for k at least 3, so 4Sum comes out to O(n^3).
Can you avoid changing the input array?
Copy the array first and sort the copy. That costs O(n) extra space and leaves the caller's array untouched. The O(n^3) time bound stays the same.
Can 4Sum be solved faster than O(n^3)?
I do not know a general method that beats O(n^3) for arbitrary input, and interviews expect this bound. Say that the fix-two-then-scan reduction is the standard answer, then explain why it fits n up to 200.

4Sum FAQ

What is the time complexity of 4Sum?

The sorted two-pointer solution runs in O(n^3) time, where n is the array length. Sorting adds O(n log n), which the cubic scan absorbs. The brute force over all index sets runs in O(n^4).

Why use two pointers for 4Sum?

Once two values are fixed, the last two must sum to a fixed remainder on a sorted range. Two pointers from both ends find every such pair in linear time, because each move discards a candidate that cannot work.

Can 4Sum be solved in O(1) extra space?

The search itself needs only a few integers, so the extra space is O(1) apart from the sort. The sort's internal memory depends on the language, from O(log n) stack in an in-place quicksort to O(n) in Python's Timsort. The output list is not counted.

Why does 4Sum need duplicate skipping?

The answer asks for unique value combinations, and repeated values would produce the same list many times. Skipping a repeated first index, second index or pointer value keeps only the first copy of each group.

Is 4Sum the same as 3Sum with one more loop?

Yes in structure: each extra fixed value adds one loop around the 2Sum scan. This solution fixes two values, so it has two loops around one pointer scan.

Asked at

See which companies ask this — Pro

Practise it