Enumerate All Index Pairs Adding Up to a Goal Value
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests hash-map indexing of duplicate values to list every index pair i < j whose values sum to a goal, in a specific sorted output order.
Enumerate All Index Pairs Adding Up to a Goal Value
You are given a list of integers values and an integer goal. Return every pair of positions [i, j] in the list such that i < j and values[i] + values[j] == goal.
The list may contain repeated numbers, and each position counts separately. Every qualifying combination of positions must be reported, not just one match per value. For instance, with values = [1, 1, 1] and goal = 2, the pairs [0, 1], [0, 2] and [1, 2] all qualify.
Output format
- Return a list of two-element lists
[i, j], each withi < j. - Each pair appears exactly once.
- Order the pairs by
iascending, and for equalibyjascending. - An element cannot be paired with itself (the same position cannot be used twice).
- If no pair qualifies, or the list has fewer than two elements, return an empty list.
Constraints
1 <= len(values) <= 10^4-10^6 <= values[i] <= 10^6-2 * 10^6 <= goal <= 2 * 10^6
Examples
Example 1
Input: find_index_pairs_with_sum([2, 7, 11, 15], 9)
Output: [[0, 1]]
Example 2
Input: find_index_pairs_with_sum([1, 2, 1, 2], 3)
Output: [[0, 1], [0, 3], [1, 2], [2, 3]]
Example 3
Input: find_index_pairs_with_sum([1, 1, 1], 2)
Output: [[0, 1], [0, 2], [1, 2]]
Hints
Hint 1
Plain Two Sum stops at the first match. Here a value can combine with every position that holds its complement, so think about storing all positions per value.
Hint 2
Build a dictionary from each value to the ascending list of positions where it occurs. Then for each i, look up goal - values[i] and consider only positions j greater than i.
Hint 3
If you iterate i upward and each stored position list is ascending, the output is automatically in the required (i, j) order. Be careful that when a value is half the goal, position i appears in its own complement list and must be skipped.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the "all pairs" variant of Two Sum. Because duplicates are allowed, a value may pair with every position holding its complement.
- Index the values. Build a dictionary mapping each value to the ascending list of positions where it appears. For
[1, 2, 1, 2]this gives{1: [0, 2], 2: [1, 3]}. - Enumerate pairs. For each position
iin increasing order, computegoal - values[i], look up its position list, and record[i, j]for everyjin that list withj > i.
Since i increases in the outer loop and each position list is already ascending, the output is automatically sorted by (i, j).
Why it is correct
- Completeness: For any valid pair
(i, j)withi < j,values[j] == goal - values[i], sojis in the list found when the loop reachesi, and it passes thej > icheck. - No duplicates: A pair is only emitted when the outer loop is at its smaller index, and each position appears once in a list.
- No self-pairing: When
values[i]is half ofgoal,iis in its own complement list, but the stricti < jtest rejects it. The test also rejectsj < i, which are mirrors of pairs already recorded.
Complexity
Let n = len(values) and P be the number of valid pairs.
- Time: O(n + P). Skipped inner steps are either
j == i(at most one peri) or mirrors of valid pairs, so total work is at most2P + n. - Space: O(n) for the dictionary plus O(P) for the output. In the worst case (all values equal and summing to the goal)
Pis about n²/2, which comes from output size, not the algorithm.
Reference solution
from typing import List
def find_index_pairs_with_sum(values: List[int], goal: int) -> List[List[int]]:
positions = {}
for index, value in enumerate(values):
positions.setdefault(value, []).append(index)
result = []
for i, value in enumerate(values):
for j in positions.get(goal - value, []):
if i < j:
result.append([i, j])
return result