First Pair Sum by Rightmost Index
Arrays & HashingAuto-graded · 21 test casesLast updated
Find two elements in an array that add up to a target sum while prioritizing the smallest second index.
Given a list of integers a and a target sum k, identify a pair of elements at distinct indices (i, j) with i < j such that a[i] + a[j] == k.
Select the pair according to the following precedence:
- Choose the valid pair that minimizes the second index
j. - If multiple pairs share the smallest index
j, choose the pair that minimizes the first indexi.
Return a list containing the values [a[i], a[j]]. If no valid pair exists, return an empty list [].
Constraints
0 <= len(a) <= 10^5-10^9 <= a[i] <= 10^9-10^9 <= k <= 10^9
Examples
Example 1
Input: earliest_pair_sum([10, 5, 2, 3, 7, 5], 10)
Output: [3, 7]
Example 2
Input: earliest_pair_sum([4, 3, 2, 3, 4], 6)
Output: [4, 2]
Example 3
Input: earliest_pair_sum([1, 2, 3], 10)
Output: []
Hints
Hint 1
Iterating through the array from left to right allows you to evaluate each index as a potential second index j.
Hint 2
You can track previously seen elements in a hash map to check for a matching complement in O(1) time.
Hint 3
To guarantee the minimal i index on ties, store only the first occurrence of each distinct number in your map.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To satisfy the condition of minimizing the second index $j$, process the list sequentially from left to right, treating each element at index $j$ as the candidate for the second element. The very first element $a[j]$ that pairs with a previously encountered element $a[i]$ ($i < j$) to equal $k$ yields the optimal $j$.
To perform this check efficiently:
- Maintain a hash map
first_seenmapping each unique value to the index of its first occurrence. - At each index $j$ with value $v$, calculate
complement = k - v. - If
complementis present infirst_seen, the pair is found. Return[complement, v]. - Otherwise, if $v$ is not yet in
first_seen, storefirst_seen[v] = j.
Checking for the complement before adding the current element ensures that $i < j$ (an element is never paired with itself). Storing only the first occurrence ensures that if multiple valid $i$ indices exist for the same $j$, the smallest index $i$ is chosen.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of
a. We iterate through the array once, performing $\mathcal{O}(1)$ average-time dictionary lookups and insertions. - Space Complexity: $\mathcal{O}(N)$ to store seen elements in the hash map.
Solution Code
from typing import List
def earliest_pair_sum(a: List[int], k: int) -> List[int]:
first_seen = {}
for j, val in enumerate(a):
complement = k - val
if complement in first_seen:
return [a[first_seen[complement]], val]
if val not in first_seen:
first_seen[val] = j
return []