KatInterview

Locate Two Entries Adding Up to a Goal Value

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashinghash-maparraycomplement-lookup

Last updated

Find two different positions in an integer list whose values sum to a goal, using a deterministic tie-break rule, which tests complement lookup with a hash map.

Pair of positions with a given sum

You are given a list of integers values and an integer goal. Find two different positions i and j in the list, with i < j, such that values[i] + values[j] == goal.

Return the positions as a list [i, j], using 0-based indexing. If no such pair exists, return an empty list [].

Which pair to return

Several valid pairs can exist, and the answer must be exactly one of them. Pick it as follows:

  1. Choose the pair with the smallest second position j. In other words, scan the list from left to right and stop at the first position j that has some earlier position i < j with values[i] + values[j] == goal.
  2. If several earlier positions qualify for that j, use the largest such i (the most recent one).

The result is always in the form [i, j] with i < j.

Notes

  • Negative numbers, zeros and repeated values can all appear.
  • A single position cannot be used twice. For example, values = [3] with goal = 6 has no answer.
  • Two equal values at different positions form a valid pair, e.g. [3, 3] with goal = 6 gives [0, 1].

Constraints

  • 1 <= len(values) <= 10^5
  • -10^9 <= values[i], goal <= 10^9
  • The function must run fast enough for the largest input, so checking every pair is too slow.

Examples

Example 1

Input: find_pair_indices([2, 7, 11, 15], 9)

Output: [0, 1]

Example 2

Input: find_pair_indices([3, 2, 4], 6)

Output: [1, 2]

Example 3

Input: find_pair_indices([3, 3], 6)

Output: [0, 1]

Hints

Hint 1

Checking every pair costs O(n^2), which is too slow for 10^5 elements. Think about what you need to know about each element when you reach it.

Hint 2

When you stand at position j, you need to know whether the value goal - values[j] appeared earlier, and where. A dictionary from value to index answers this in O(1) on average.

Hint 3

Check the dictionary before inserting the current value, otherwise an element can pair with itself. Overwriting the stored index on each insert keeps the most recent position, which matches the tie-break rule.