KatInterview

Distinct Value Foursomes Hitting a Target Total

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingdeduplication

Last 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.