Find the Earliest Pair with a Target Sum
AmazonSoftware Engineer · Technical ScreenLast updated
Tests array traversal and hash table lookups to find a two-sum pair that minimizes the second index, running in linear time and space.
Problem Statement
Given an array of integers nums and an integer target, find a pair of elements at distinct indices (i, j) with i < j such that nums[i] + nums[j] == target.
Among all valid pairs (i, j):
- Choose the pair that minimizes the second index
j. - If there is a tie for the smallest
j, choose the pair that minimizes the first indexi.
Return the values as a list [nums[i], nums[j]]. If no such pair exists, return an empty list [].
Function Signature
def earliest_pair_sum(nums: list[int], target: int) -> list[int]:
pass
Examples
Example 1
Input: nums = [10, 5, 2, 3, 7, 5], target = 10
Output: [3, 7]
Explanation:
- Pair at indices (1, 5): nums[1] + nums[5] = 5 + 5 = 10 (j = 5)
- Pair at indices (3, 4): nums[3] + nums[4] = 3 + 7 = 10 (j = 4)
Since index 4 < 5, the pair [3, 7] has the earlier second index.
Example 2
Input: nums = [4, 3, 2, 3, 4], target = 6
Output: [4, 2]
Explanation:
Valid pairs summing to 6 are:
- (0, 2): 4 + 2 = 6 (j = 2)
- (1, 3): 3 + 3 = 6 (j = 3)
- (2, 4): 2 + 4 = 6 (j = 4)
The pair with the smallest second index is at (0, 2), so the output is [4, 2].
Example 3
Input: nums = [1, 2, 3], target = 10
Output: []
Explanation: No two elements sum to 10.
Constraints
0 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9
Hints
Hint 1
Minimizing the second index j means that scanning left-to-right will identify the optimal j at the very first moment a valid complement has already been seen.
Hint 2
Use a hash map to record elements you have seen so far, mapping each value to its index.
Hint 3
If a value appears multiple times, keeping only its first occurrence guarantees that you also minimize the first index i in case of duplicate candidates.
Follow-up questions
- How would your approach change if you were required to solve this in O(1) auxiliary space?
- If the input array were guaranteed to be sorted, how could you optimize the space complexity while maintaining O(n) time?
- How would you adapt this solution for a streaming data input where elements arrive one at a time and you must report the first valid pair immediately?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.