Sobes.tech
Middle — Senior

How is the problem of finding a pair of numbers with a given sum solved?

sobes.tech AI

Answer from AI

Task: find a pair of numbers in an array whose sum equals a given number.

Classic solution:

  • Checking all pairs — O(n²), inefficient.

Optimal solution using a hash table (dictionary):

  1. Create an empty hash table.
  2. Iterate through the array, for each element x, check if target - x exists in the table.
  3. If it exists — found a pair.
  4. If not — add x to the table and continue.

Complexity: O(n) in time and O(n) in space.

Example in Python:

def find_pair(nums, target):
    seen = set()
    for num in nums:
        complement = target - num
        if complement in seen:
            return (complement, num)
        seen.add(num)
    return None

This solution is efficient and widely used in problems involving finding pairs with a given sum.