Distinct Value Foursomes Hitting a Target Total
Arrays & HashingAuto-graded · 21 test casesLast updated
Find every distinct set of four values, taken from different positions, that add up to a target, with no repeated value combinations in the output.
Distinct Foursomes With a Given Total
You are given a list of integers values and an integer goal. Find every combination of four numbers from the list whose sum equals goal, and return them as a list of four-element lists.
Rules
- The four numbers must come from four different positions in
values. The same position cannot be used twice, but equal values at different positions are allowed. - Each combination of values must appear at most once in the result. Two foursomes count as the same if they contain the same multiset of numbers, regardless of which positions supplied them.
- Each inner list must be in non-decreasing order.
- The outer list may be in any order, although the reference output lists the foursomes in ascending lexicographic order.
- If no valid foursome exists (including when the list has fewer than four elements), return an empty list.
- The input list must not be changed in any way that affects the caller.
Input
values: a list of integers.goal: an integer.
Output
A list of lists of four integers, each inner list sorted in non-decreasing order, containing every distinct valid foursome exactly once.
Constraints
1 <= len(values) <= 200-10^9 <= values[i] <= 10^9-10^9 <= goal <= 10^9
Examples
Example 1
Input: distinct_quad_sums([1, 0, -1, 0, -2, 2], 0)
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Example 2
Input: distinct_quad_sums([2, 2, 2, 2, 2], 8)
Output: [[2, 2, 2, 2]]
Hints
Hint 1
Sort a copy of the list first. Sorting puts equal values next to each other, which makes it easy to avoid emitting the same combination twice.
Hint 2
Fix the two smallest members of the foursome with two nested loops, then look for the remaining two with a left pointer and a right pointer moving inward over the rest of the sorted list.
Hint 3
To avoid duplicates, skip a fixed value if it equals the previous one at the same loop level (careful: the second loop must only compare against the previous value within its own range), and after recording a match move both pointers past any equal values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Sort a copy of the input. Sorting groups equal values together and lets us reason about sums using order.
- Fix the two smallest members of the foursome using indices
i < j. - Find the other two with two pointers. Set
left = j + 1andright = n - 1. Compute the sum of the four chosen values:- If it equals
goal, record the foursome, move both pointers inward, and keep moving them while they point at values equal to the one just used. - If it is too small, move
leftright to increase the sum. - If it is too large, move
rightleft to decrease the sum.
- If it equals
- Skip duplicates at every level. Skip
iif it equals the previous element. Skipjif it equals the previous element andj > i + 1. Thej > i + 1condition matters: it still allowsjto take the same value asi(as in[2, 2, 2, 2]). - Prune using the sorted order. For a fixed prefix, if the smallest possible total already exceeds
goal, break out of that loop, since later choices are only larger. If the largest possible total is still belowgoal, continue to the next index. Pruning compares full sums, so it is valid with negative numbers.
Why it is correct
- Completeness: any valid foursome, written in sorted order, has a first and second value. The loops reach the first occurrence of each of these values (duplicate skipping only discards later copies). For that fixed pair, the two-pointer scan never discards a valid pair: if the current sum is too small, no pairing of the current
leftwith any index up torightcan work, soleftcan move; the symmetric argument holds forright. - Uniqueness: each value is used at most once as the choice at each of the four positions, because the
iandjloops skip repeats and the pointers jump over repeats after a match. Since the array is sorted, every foursome is produced in non-decreasing order, so equal value sets give identical lists. - Pruning is safe:
breakonly fires when the minimum achievable sum for all later choices already exceedsgoal;continueonly skips the current index.
Complexity
- Time: O(n^3). There are O(n^2) pairs
(i, j), each followed by an O(n) two-pointer scan. Sorting adds O(n log n). - Space: O(n) for the sorted copy, excluding the output.
Reference solution
from typing import List
def distinct_quad_sums(values: List[int], goal: int) -> List[List[int]]:
nums = sorted(values)
n = len(nums)
result = []
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > goal:
break
if nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < goal:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > goal:
break
if nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < goal:
continue
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == goal:
result.append([nums[i], nums[j], nums[left], nums[right]])
left += 1
right -= 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < goal:
left += 1
else:
right -= 1
return result