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):
- Create an empty hash table.
- Iterate through the array, for each element
x, check iftarget - xexists in the table. - If it exists — found a pair.
- If not — add
xto 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.