KatInterview

Earliest-Completing Pair That Hits a Target Sum

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashinghash-maptwo-sumduplicates

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

  1. Pick the pair with the smallest right index j.
  2. Among pairs with that same j, pick the one with the smallest left index i.

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 using O(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.