KatInterview

First Pair Sum by Rightmost Index

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashingarrayshash-tabletwo-pointers

Last 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:

  1. Choose the valid pair that minimizes the second index j.
  2. If multiple pairs share the smallest index j, choose the pair that minimizes the first index i.

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.