Locate Two Entries Adding Up to a Goal Value
Arrays & HashingAuto-graded · 21 test casesLast updated
Find two different positions in an integer list whose values sum to a goal, using a deterministic tie-break rule, which tests complement lookup with a hash map.
Pair of positions with a given sum
You are given a list of integers values and an integer goal. Find two different positions i and j in the list, with i < j, such that values[i] + values[j] == goal.
Return the positions as a list [i, j], using 0-based indexing. If no such pair exists, return an empty list [].
Which pair to return
Several valid pairs can exist, and the answer must be exactly one of them. Pick it as follows:
- Choose the pair with the smallest second position
j. In other words, scan the list from left to right and stop at the first positionjthat has some earlier positioni < jwithvalues[i] + values[j] == goal. - If several earlier positions qualify for that
j, use the largest suchi(the most recent one).
The result is always in the form [i, j] with i < j.
Notes
- Negative numbers, zeros and repeated values can all appear.
- A single position cannot be used twice. For example,
values = [3]withgoal = 6has no answer. - Two equal values at different positions form a valid pair, e.g.
[3, 3]withgoal = 6gives[0, 1].
Constraints
1 <= len(values) <= 10^5-10^9 <= values[i], goal <= 10^9- The function must run fast enough for the largest input, so checking every pair is too slow.
Examples
Example 1
Input: find_pair_indices([2, 7, 11, 15], 9)
Output: [0, 1]
Example 2
Input: find_pair_indices([3, 2, 4], 6)
Output: [1, 2]
Example 3
Input: find_pair_indices([3, 3], 6)
Output: [0, 1]
Hints
Hint 1
Checking every pair costs O(n^2), which is too slow for 10^5 elements. Think about what you need to know about each element when you reach it.
Hint 2
When you stand at position j, you need to know whether the value goal - values[j] appeared earlier, and where. A dictionary from value to index answers this in O(1) on average.
Hint 3
Check the dictionary before inserting the current value, otherwise an element can pair with itself. Overwriting the stored index on each insert keeps the most recent position, which matches the tie-break rule.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the list once from left to right while keeping a dictionary that maps each value seen so far to the most recent index where it appeared.
For the element x at position j:
- Compute
need = goal - x. - If
needis in the dictionary, return[last_index[need], j]. - Otherwise store
last_index[x] = jand continue.
If the loop ends with no match, return [].
Why it is correct
- Valid answer. The stored index always comes from a position strictly before
j, soi < jand the two positions are different. The values sum togoalbecauseneed + x == goal. - Smallest second position. The scan goes left to right and returns at the first
jthat has a partner, so no smallerjcould have worked. - Largest first position. Each insertion overwrites the previous index for that value, so the dictionary holds the latest earlier index for
need. This matches the tie-break rule. - No self-pairing. The lookup happens before the insertion, so the current element is never matched with itself.
- No pair exists. If a valid pair
(i, j)existed, the scan would have found a partner atjor earlier. So reaching the end means no pair exists.
Complexity
- Time: O(n) on average, with one pass and O(1) average dictionary operations.
- Space: O(n) for the dictionary.
Reference solution
from typing import List
def find_pair_indices(values: List[int], goal: int) -> List[int]:
last_index = {}
for j, x in enumerate(values):
need = goal - x
if need in last_index:
return [last_index[need], j]
last_index[x] = j
return []