KatInterview

Locate the Two Positions That Add Up to a Goal Value

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

Last updated

Find the single pair of distinct positions in an integer list whose values add up to a goal, using a one-pass lookup instead of checking every pair.

You are given a list of integers values and an integer goal. Exactly one pair of positions in the list holds numbers that add up to goal. Find that pair of positions.

Task

Return a list [a, b] where:

  • a < b, so the smaller position comes first.
  • values[a] + values[b] == goal.

Rules

  • Positions are 0-based.
  • A single position cannot be used twice. However, two different positions that hold the same number may together form the pair.
  • The input is guaranteed to contain exactly one pair of positions a < b with values[a] + values[b] == goal.
  • Return the answer as a list of two integers.

Constraints

  • 2 <= len(values) <= 10000
  • -10^9 <= values[i] <= 10^9
  • -10^9 <= goal <= 10^9
  • Exactly one valid pair of positions exists.

Examples

Example 1

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

Output: [0, 1]

Example 2

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

Output: [1, 2]

Example 3

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

Output: [0, 1]

Hints

Hint 1

Checking every pair of positions works but takes quadratic time. For a fixed element x, what single number would its partner have to be?

Hint 2

Walk through the list once while remembering the numbers you have already passed and where you saw them. A dictionary from number to position makes the partner check fast.

Hint 3

Check for the partner before storing the current number. This prevents a position from pairing with itself while still letting equal numbers at different positions match. Also, position 0 is a valid answer, so compare against None rather than relying on truthiness.