KatInterview

Locate Two Entries That Add Up to a Goal

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

Last updated

Find the two distinct positions in an integer list whose values sum to a goal, using a single-pass hash map lookup instead of checking every pair.

Locate Two Entries That Add Up to a Goal

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

The input is guaranteed to contain exactly one such pair of positions. The same position cannot be used twice, but two different positions may hold equal numbers.

Output format

Return a list of two integers [i, j] with i < j, so the smaller index comes first.

Constraints

  • 2 <= len(values) <= 10^4
  • -10^9 <= values[k] <= 10^9
  • -10^9 <= goal <= 10^9
  • Exactly one pair of distinct indices satisfies the sum condition.
  • Values may be negative or zero, and may repeat.
  • Aim for better than checking every pair; a linear-time solution is expected.

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 works but takes quadratic time. Try asking, for each element, whether the number that would complete it has already appeared.

Hint 2

For the current value v, the number you need is goal - v. A dictionary from value to index lets you test for it in constant average time.

Hint 3

Check the dictionary before inserting the current value. That prevents an element from pairing with itself and still handles duplicates such as [3, 3] with goal 6.