Four-Position Target Sum Finder Preserving Original Indices
Arrays & HashingAuto-graded · 25 test casesLast 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
afirst, thenb, thenc, thend). - 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^9in 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The usual "sort and use two pointers while skipping duplicates" technique does not work here. Sorting destroys the original positions, and skipping duplicate values would discard answers that are required (for example, an array of five equal numbers has five distinct valid index sets).
Instead, split each quadruple (a, b, c, d) at the second index b:
- a left part
(a, b)witha < b - a right pair
(c, d)withb < c < d
Keep a dictionary that maps a pair sum to the list of all index pairs (c, d) with that sum. For a fixed (a, b), a single lookup of goal - values[a] - values[b] returns every compatible right pair.
The only difficulty is making sure the right pair starts after b. To do this, sweep b from n - 3 down to 1. Before handling a given b, insert all pairs whose first index is exactly b + 1. After that insertion, the dictionary contains precisely the pairs (c, d) with c > b.
Finally, sort the collected results lexicographically.
Why it is correct
- Invariant: when processing
b, the dictionary holds exactly the pairs(c, d)withb < c < d. Each step of the sweep adds the pairs starting atb + 1, so the invariant holds by induction. - Soundness: every reported
[a, b, c, d]hasa < bfrom the loop range andb < c < dfrom the invariant. The sum isvalues[a] + values[b] + (goal - values[a] - values[b]) = goal. - Completeness and uniqueness: a valid quadruple is produced only when the sweep is at its own
b. At that moment its(c, d)pair is in the dictionary, so it is found, and only once. - Pairs are stored as lists rather than counts, so equal values at different positions remain separate answers.
- When
n < 4the range forbis empty and the result is[]with no special case.
Complexity
Let Q be the number of valid quadruples (at most 10^4).
- Time:
O(n^2 + Q log Q). Building the dictionary inserts each pair once, the(a, b)loops performO(n^2)lookups, emitting answers costsO(Q), and the final sort costsQ log Q. - Space:
O(n^2 + Q)for the dictionary and the output.
Reference solution
from typing import List
def four_index_sum_matches(values: List[int], goal: int) -> List[List[int]]:
n = len(values)
res = []
# pair_map[s] = list of (c, d) with c > current b, c < d, values[c] + values[d] == s
pair_map = {}
for b in range(n - 3, 0, -1):
c = b + 1
vc = values[c]
for d in range(c + 1, n):
s = vc + values[d]
lst = pair_map.get(s)
if lst is None:
pair_map[s] = [(c, d)]
else:
lst.append((c, d))
rem = goal - values[b]
for a in range(b):
lst = pair_map.get(rem - values[a])
if lst:
for c2, d2 in lst:
res.append([a, b, c2, d2])
res.sort()
return res