KatInterview

Find Pair with Given Sum

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashinghash-tabletwo-pointersarray

Last updated

Tests the ability to use hash-based lookups for constant-time complement checking and handle input validation rigorously.

Write a function that determines whether an array contains two elements at different positions that add up to a specified target value.

You are given an array of integers numbers and an integer target_sum. Your task is to return True if there exist two different indices i and j where numbers[i] + numbers[j] == target_sum. If no such pair exists, return False.

Input validation requirements:

  • Return False if the input array is None
  • Return False if the array contains fewer than two elements
  • Return False if any element in the array is not a valid integer (including booleans, which should be rejected despite being a subclass of int in Python)

Additional constraints:

  • Do not modify the input array
  • Your solution must achieve O(n) time complexity
  • Your solution must use O(n) space complexity

Constraints

  • 0 ≤ len(numbers) ≤ 10^5
  • -10^9 ≤ numbers[i] ≤ 10^9
  • -10^9 ≤ target_sum ≤ 10^9
  • All elements must be integers (booleans are not valid)
  • The same element cannot be used twice (must use two distinct indices)

Examples

Example 1

Input: find_pair_sum([10, 15, 3, 7], 17)

Output: True

Example 2

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

Output: True

Hints

Hint 1

Consider what value would need to pair with each element to reach the target sum

Hint 2

A hash set allows you to check for the existence of a complement in constant time

Hint 3

Process elements in order and check for the complement before adding the current element to your tracking structure