Given an integer array nums of length n and an integer target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
-
0 <= a, b, c, d < n
-
a
,
b
,
c
and
d
are distinct indices.
-
nums[a] + nums[b] + nums[c] + nums[d] == target
Two quadruplets are the same when they contain the same values, whichever indices produced them. Each quadruplet must appear in the result only once.
Function Signature
def four_sum(nums: list[int], target: int) -> list[list[int]]:
Rules
-
Write each quadruplet with its four values in non-decreasing order.
-
Sort the list of quadruplets in ascending lexicographic order.
-
Values in
nums
may repeat. A value can appear in a quadruplet as many times as it occurs in
nums
, since each position is used at most once.
-
Return an empty list when no quadruplet sums to
target
.
Constraints
-
1 <= len(nums) <= 200
-
-10^9 <= nums[i] <= 10^9
-
-10^9 <= target <= 10^9
Examples
Input: nums = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Of the 15 ways to pick four positions, only these three value combinations sum to 0. The two zeros sit at different positions, so [-2, 0, 0, 2] and [-1, 0, 0, 1] are both valid.
Input: nums = [2, 2, 2, 2, 2], target = 8
Output: [[2, 2, 2, 2]]
There are five ways to choose four of the five positions, but every choice gives the same values, so the quadruplet is listed once.
Input: nums = [1, 2, 3], target = 6
Output: []
The array has fewer than four elements, so no quadruplet exists.