4Sum

Medium · Arrays & Hashing · Array · Two Pointers · Sorting

Problem

You are given an integer array nums and an integer target. Return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that a, b, c and d are four distinct indices and the four values add up to target.

Quadruplets are compared by their values: the result must not contain two quadruplets made of the same four values. The quadruplets, and the values inside each one, may be in any order.

Examples

Input: nums = [3,-1,0,2,-2,1], target = 2
Output: [[-2,-1,2,3],[-2,0,1,3],[-1,0,1,2]]

Three different groups of values add up to 2, for example -2 + -1 + 2 + 3.

Input: nums = [2,2,2,2,2], target = 8
Output: [[2,2,2,2]]

Many choices of four indices exist, but they all give the same values, so the quadruplet is listed once.

Input: nums = [1,2,3,4], target = 100
Output: []

The four values together add up to only 10.

Constraints

Approaches

Follow-up

The same structure handles k values for any k: fix one value, solve (k - 1)-sum on the rest, and finish with two pointers at k = 2. That costs O(n^(k-1)). If only the number of quadruplets is wanted and they come from four different lists, a hash map of pair sums brings it down to O(n²); see the first use case.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…