Earliest-Completing Pair That Hits a Target Sum
Arrays & HashingAuto-graded · 25 test casesLast updated
Find the pair of indices whose values sum to a target, choosing the pair that finishes earliest in the array, with deterministic duplicate handling, using a one-pass hash map.
Earliest-Completing Pair That Hits a Target Sum
You are given a list of integers values and an integer target. Walk through the list from left to right and find the first moment at which the prefix contains two entries adding up to target.
Task
Write find_earliest_pair(values, target) that returns a two-element list [i, j] of zero-based indices such that:
i < j, so the two indices are distinct,values[i] + values[j] == target.
If several pairs qualify, choose using these rules in order:
- Pick the pair with the smallest right index
j. - Among pairs with that same
j, pick the one with the smallest left indexi.
The ordering is by the right index first, not the left. For values = [1, 2, 4, 5] and target = 6, the valid pairs are [0, 3] and [1, 2]. The answer is [1, 2], because its right index 2 is smaller than 3.
If no valid pair exists (including when the list has fewer than two elements), return an empty list [].
The input list must not be modified.
Constraints
0 <= len(values) <= 200,000-1,000,000,000 <= values[k], target <= 1,000,000,000- Sums can reach about 2 * 10^9 in magnitude, so use integer types wide enough to hold them (64-bit in fixed-width languages).
- An
O(n)expected-time solution usingO(n)extra space is the intended target. - Do not mutate
values.
Examples
Example 1
Input: find_earliest_pair([4, 1, 5, 3, 3], 6)
Output: [1, 2]
Example 2
Input: find_earliest_pair([2, 2], 4)
Output: [0, 1]
Example 3
Input: find_earliest_pair([1, 2, 3], 10)
Output: []
Hints
Hint 1
If you fix the right index j, every valid left index must hold the value target - values[j]. What would you need to remember about earlier elements to look that up quickly?
Hint 2
Check whether the needed complement has already been seen before you record the current element. This prevents an element from pairing with itself.
Hint 3
For duplicate values, store only the first (smallest) index and never overwrite it. The first j that finds a partner gives the smallest right index, and the stored index gives the smallest left index.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scan the list once from left to right, keeping a dictionary that maps each value to the first index where it appeared among the elements already processed.
At each index j:
- Compute
need = target - values[j]. - If
needis already in the dictionary, return[first_seen[need], j]immediately. - Otherwise, store
values[j] -> j, but only if that value is not yet in the dictionary.
Why it is correct
- Smallest right index. We return at the first
jthat has any valid partner to its left. If a valid pair with a smaller right index existed, the scan would have returned earlier. - Smallest left index for that
j. All partners ofjhave the same valueneed. The dictionary stores the earliest index of each value invalues[0..j-1], sofirst_seen[need]is the smallest possiblei. - Distinct indices. We look up before inserting, so the partner always comes from a strictly earlier position. A single element never matches itself, while two equal values at different positions (such as
[2, 2]with target4) do match. - Duplicates. Never overwriting an entry keeps the smallest left index. With
[2, 2, 2]and target4, the answer is[0, 1], not[1, 2]. - No pair. If the loop ends without a hit, return
[].
Why not iterate over a map?
Building a full value-to-index map and then picking the first match while iterating over the map is fragile. Map iteration order does not reflect index order, and in many languages it depends on hashing and resizing. A plain overwrite also keeps the last index instead of the first. Driving the loop by array index makes the result depend only on positions.
Comparison with sorting
Sorting a copy of (value, index) pairs and using two pointers costs O(n log n) time and O(n) space. It loses the scan order, so you would have to enumerate all matching value groups and compare the candidate pairs under the required ordering. The hash approach gets the ordering for free from the scan.
Complexity
- Time:
O(n)expected, withO(1)average work per element. - Space:
O(n)for the dictionary.
Reference solution
from typing import List
def find_earliest_pair(values: List[int], target: int) -> List[int]:
first_seen = {} # value -> smallest index at which it appears so far
for j, v in enumerate(values):
need = target - v
if need in first_seen:
return [first_seen[need], j]
if v not in first_seen:
first_seen[v] = j
return []