You get an integer array nums and an integer target. Find every group of four numbers, taken from four different positions in the array, whose sum is exactly target, and return the groups as quadruplets.
Two quadruplets that hold the same four values count as one, even when they come from different positions: list each set of values only once. A value can appear more than once in a quadruplet only as many times as it appears in nums.
You may return the quadruplets in any order, and the four numbers inside each quadruplet in any order too.
Each of the four groups adds up to 5, for example -3 + 1 + 2 + 5. No other choice of four positions does.
There are fifteen ways to pick four of the six positions, but every one of them gives the same values, so the quadruplet appears once.
[]
The only possible group uses all four numbers, and it sums to 8.
Constraints
1 <= nums.length <= 200-10⁹ <= nums[i] <= 10⁹-10⁹ <= target <= 10⁹Once two of the four numbers are chosen, what remains is a problem you may already know: find two more numbers that add up to what is left. Sorting the array makes that search, and skipping repeated values, much easier.
Four numbers is a lot to juggle at once, so don't. Choose two of them, and the job shrinks to something smaller: find two more numbers whose sum is target minus the two you chose. That smaller job is a pair search, and a pair search on a sorted array is quick.
Time O(n³)Space O(n)
The full walkthrough and code are part of Premium