Locate the Two Positions That Add Up to a Goal Value
Arrays & HashingAuto-graded · 25 test casesLast updated
Find the single pair of distinct positions in an integer list whose values add up to a goal, using a one-pass lookup instead of checking every pair.
You are given a list of integers values and an integer goal. Exactly one pair of positions in the list holds numbers that add up to goal. Find that pair of positions.
Task
Return a list [a, b] where:
a < b, so the smaller position comes first.values[a] + values[b] == goal.
Rules
- Positions are 0-based.
- A single position cannot be used twice. However, two different positions that hold the same number may together form the pair.
- The input is guaranteed to contain exactly one pair of positions
a < bwithvalues[a] + values[b] == goal. - Return the answer as a list of two integers.
Constraints
2 <= len(values) <= 10000-10^9 <= values[i] <= 10^9-10^9 <= goal <= 10^9- Exactly one valid pair of positions exists.
Examples
Example 1
Input: find_pair_positions([2, 7, 11, 15], 9)
Output: [0, 1]
Example 2
Input: find_pair_positions([3, 2, 4], 6)
Output: [1, 2]
Example 3
Input: find_pair_positions([3, 3], 6)
Output: [0, 1]
Hints
Hint 1
Checking every pair of positions works but takes quadratic time. For a fixed element x, what single number would its partner have to be?
Hint 2
Walk through the list once while remembering the numbers you have already passed and where you saw them. A dictionary from number to position makes the partner check fast.
Hint 3
Check for the partner before storing the current number. This prevents a position from pairing with itself while still letting equal numbers at different positions match. Also, position 0 is a valid answer, so compare against None rather than relying on truthiness.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking every pair of positions costs O(n^2), which is around 50 million comparisons for the largest input. We can do better by turning the search into a lookup.
For the number v at position j, its partner must equal goal - v. So the real question is: have we already seen goal - v, and where?
Scan the list once, keeping a dictionary from number to the earliest position where it appeared. For each position j with number v:
- Look up
goal - vin the dictionary. - If it is found at position
i, return[i, j]. - Otherwise, store
v -> junlessvis already stored.
Why it is correct
- The pair is found. Let the unique valid pair be
(a, b)witha < b. When the scan reachesb, positionahas already been processed, sovalues[a]is in the dictionary. The partner ofvalues[b]is exactlyvalues[a], so the lookup succeeds. An earlier success would imply a different valid pair, which the guarantee rules out. - No self-pairing. The lookup happens before the insertion, so when handling position
jthe dictionary only describes positions strictly less thanj. - Equal numbers work. For
[3, 3]with goal 6, position 0 stores3. At position 1 the partner3is found, giving[0, 1]. - Ordering. The stored position always comes from an earlier step, so the result is automatically
[smaller, larger]. - Duplicates. Keeping the first position of each number is safe, because needing a later copy would imply more than one valid pair.
- Position 0. Compare with
Noneexplicitly, since0is falsy in Python.
Complexity
- Time: O(n) on average, with one pass and constant expected work per dictionary operation.
- Space: O(n) for the dictionary.
Reference solution
from typing import List
def find_pair_positions(values: List[int], goal: int) -> List[int]:
# Maps a number to the earliest position where it appeared.
first_pos = {}
for j, v in enumerate(values):
# Look for the partner before storing v, so a position
# can never be matched with itself.
i = first_pos.get(goal - v)
if i is not None:
return [i, j]
if v not in first_pos:
first_pos[v] = j
return []