Menu
CoddyTech

4Sum

You get a list of integers nums and an integer target. Return every quadruplet [a, b, c, d] whose four values sit at four different positions of nums and add up to target. Write each quadruplet with its values in non-decreasing order. If the same four values can be picked from different positions, the quadruplet still appears once. Sort the answer by first value, then second, then third. When no quadruplet works, return an empty list.

Function

fourSum(nums: integer-array, target: integer) → integer-2d-array
numsinteger-array
the numbers to pick from, at least one
targetinteger
the sum each quadruplet must reach
Returnsinteger-2d-array
the distinct quadruplets with sum target, each one sorted, the list sorted too; an empty list if there are none

Constraints

  • 1 ≤ nums.length ≤ 200
  • -108 ≤ nums[i] ≤ 108
  • -109 ≤ target ≤ 109
  • The sum of any four values lies between -4 × 108 and 4 × 108, so it fits in a 32-bit integer.
  • Quadruplets that hold the same four values count as one.

Examples

Input
nums = [3, -1, 0, 2, -2, 1, -3]target = 1
Output
[[-3, -1, 2, 3], [-3, 0, 1, 3], [-2, -1, 1, 3], [-2, 0, 1, 2]]
Explanation
Each of the four quadruplets adds up to 1, for example -3 + (-1) + 2 + 3. The two that start with -3 come first, ordered by their second value: -1 before 0.
challenge icon

Follow-up

Count the sets of four positions whose values add up to target, rather than the distinct quadruplets. The second example has 15. Can you do it in O(n²)?

Reset code
def fourSum(nums, target):
    # Write code here

Test #1

Test #2

Test #3

Arguments

nums = [3, -1, 0, 2, -2, 1, -3]
target = 1

Expected Output

[[-3, -1, 2, 3], [-3, 0, 1, 3], [-2, -1, 1, 3], [-2, 0, 1, 2]]