KatInterview

Pair Sum Existence Check in an Integer List

Arrays & HashingAuto-graded · 24 test cases
EasyAuto-gradedArrays & Hashinghash-settwo-sumarrays

Last updated

Decide whether any two elements at different positions in an integer list add up to a given value, testing hash-set lookups and careful handling of duplicates.

You are given a list of integers values and an integer goal.

Write a function that returns True if there are two elements at different positions in the list whose sum equals goal, and False otherwise.

Details

  • "Different" refers to positions, not numeric values. Two equal numbers that sit at separate indices can form a valid pair. For example, [3, 3] with a goal of 6 gives True.
  • A single element cannot be paired with itself. For example, [3] with a goal of 6 gives False, and [0] with a goal of 0 gives False.
  • Values may be negative or zero.
  • If the list is empty or has only one element, the answer is False.
  • The function only needs to return a boolean. It does not need to report which elements were used.

Constraints

  • 0 <= len(values) <= 10^5
  • Each element of values and the value of goal are integers that fit comfortably in standard integer arithmetic (Python integers do not overflow).
  • The list may contain duplicates and is not guaranteed to be sorted.
  • Aim for better than quadratic time.

Examples

Example 1

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

Output: True

Example 2

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

Output: True

Example 3

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

Output: True

Example 4

Input: has_pair_with_sum([1, 2, 3], 7)

Output: False

Hints

Hint 1

For any element x, exactly one other number can complete a pair with it. What is that number in terms of goal and x?

Hint 2

Walk through the list once while remembering the numbers you have already passed. What data structure answers 'have I seen this number?' in constant average time?

Hint 3

Check whether the needed partner is already remembered before you record the current number. This ordering stops an element from pairing with itself while still allowing two equal numbers at different positions to match.