KatInterview

Four-Position Target Sum Finder Preserving Original Indices

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashinghash-mapmeet-in-the-middlek-sum

Last updated

Find all increasing index quadruples whose values add up to a target, treating equal values at different positions as distinct answers; tests hashing pair sums and ordering.

You are given a list of integers values and an integer goal. Find every set of four positions a < b < c < d in the list such that values[a] + values[b] + values[c] + values[d] == goal.

Results are identified by position, not by value. The indices refer to the original, unchanged list, and two selections that happen to use equal numbers at different positions count as different results. Do not remove duplicates by value.

Aim for something noticeably better than checking every group of four positions.

Output format

  • Each result is a list [a, b, c, d] of four indices in strictly increasing order.
  • Every valid selection appears exactly once.
  • The outer list is sorted in ascending lexicographic order (compare a first, then b, then c, then d).
  • If there is no valid selection, return an empty list. This includes the case where the list has fewer than four elements.

Constraints

  • 1 <= len(values) <= 200
  • -10^9 <= values[i] <= 10^9
  • -10^9 <= goal <= 10^9
  • A sum of four elements can reach 4 * 10^9 in absolute value, which is beyond a 32-bit signed integer; use 64-bit arithmetic in fixed-width languages.
  • The number of valid index quadruples is at most 10^4.

Examples

Example 1

Input: four_index_sum_matches([1, 0, -1, 0, -2, 2], 0)

Output: [[0, 1, 2, 3], [0, 2, 4, 5], [1, 3, 4, 5]]

Example 2

Input: four_index_sum_matches([2, 2, 2, 2, 2], 8)

Output: [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [1, 2, 3, 4]]

Example 3

Input: four_index_sum_matches([1, 2, 3], 6)

Output: []

Hints

Hint 1

Sorting the array and skipping repeated values throws away exactly the information you need here, so think about a different way to split the four positions.

Hint 2

Split each quadruple into a left pair (a, b) and a right pair (c, d) with b < c. Store right pairs in a dictionary keyed by their sum, with the value being a list of index pairs.

Hint 3

Sweep b from right to left. Before processing b, insert all pairs whose first index is b + 1, so the dictionary contains only pairs that start strictly after b. Then look up goal - values[a] - values[b] for each a < b, and sort the output at the end.