Locate Two Entries That Add Up to a Goal
Arrays & HashingAuto-graded · 21 test casesLast updated
Find the two distinct positions in an integer list whose values sum to a goal, using a single-pass hash map lookup instead of checking every pair.
Locate Two Entries That Add Up to a Goal
You are given a list of integers values and an integer goal. Find two different positions i and j in the list such that values[i] + values[j] == goal, and return those positions.
The input is guaranteed to contain exactly one such pair of positions. The same position cannot be used twice, but two different positions may hold equal numbers.
Output format
Return a list of two integers [i, j] with i < j, so the smaller index comes first.
Constraints
2 <= len(values) <= 10^4-10^9 <= values[k] <= 10^9-10^9 <= goal <= 10^9- Exactly one pair of distinct indices satisfies the sum condition.
- Values may be negative or zero, and may repeat.
- Aim for better than checking every pair; a linear-time solution is expected.
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 works but takes quadratic time. Try asking, for each element, whether the number that would complete it has already appeared.
Hint 2
For the current value v, the number you need is goal - v. A dictionary from value to index lets you test for it in constant average time.
Hint 3
Check the dictionary before inserting the current value. That prevents an element from pairing with itself and still handles duplicates such as [3, 3] with goal 6.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking every pair of positions costs O(n²). We can do better by changing the question we ask at each step. Instead of "which later element pairs with this one?", ask "have I already seen the number that completes this one?"
Scan the list from left to right while keeping a dictionary that maps each number to the index where it was seen. At index j with value number:
- Compute
needed = goal - number. - If
neededis already in the dictionary, return[seen[needed], j]. - Otherwise store
seen[number] = jand move on.
Why it is correct
- Every valid pair is found. Suppose the answer is at indices
i < j. When the scan reachesj, indexihas already been processed, sovalues[i]is in the dictionary. The lookup forgoal - values[j]succeeds, so the function returns at indexjat the latest. - No element pairs with itself. The lookup happens before the insertion, so the dictionary never contains the current index when we query it.
- Duplicates work. For
[3, 3]and goal6, index 0 stores3 -> 0. At index 1 the needed value3is found, giving[0, 1]. - Ordering. The stored index is always earlier than the current one, so the result is
[smaller, larger]. Because the answer is unique, this matches the required format exactly. - Negatives and zero need no special handling, because only subtraction and equality are used.
Complexity
- Time: O(n), one pass with O(1) average-time dictionary operations.
- Space: O(n) for the dictionary in the worst case.
A sort-plus-two-pointers alternative runs in O(n log n) time and still needs O(n) space to remember the original indices, so the dictionary approach is preferred.
Reference solution
from typing import List
def find_pair_indices(values: List[int], goal: int) -> List[int]:
seen = {} # number -> index where it was last seen
for j, number in enumerate(values):
needed = goal - number
if needed in seen:
return [seen[needed], j]
seen[number] = j
raise ValueError("No valid pair")