Write a function that takes in an array of integers, which can be both positive and negative, along with a target integer. The function should return all unique pairs of integers from the array that sum up to the target integer.
Make sure that your function returns unique combinations. If the array [2, 3, 4, 6] has assigned number 5, only return (2, 3), not (2, 3), (3, 2)
Answer
from typing import List, Tuple, Set
def find_pairs_with_sum(arr: List[int], target: int) -> List[Tuple[int, int]]:
# Initialize an empty set to store unique pairs
result_set = set()
# Create a set for quick lookups
complementary_set = set()
# Iterate through the array to find pairs that sum up to the target
for num in arr:
complement = target - num
if complement in complementary_set:
# Sort the pair (smaller, larger) before adding to result set for uniqueness
result_set.add(tuple(sorted((num, complement))))
complementary_set.add(num)
# Convert the set to a list of tuples
return list(result_set)
# Test the function with the given test cases
test_cases = [
([3, 4, 2, 5], 7),
([2, 4, 1, 5], 9),
([7, 1, 2, 3, 4, -2], 5)
]
for arr, target in test_cases:
print(f"find_pairs_with_sum({arr}, {target}) = {find_pairs_with_sum(arr, target)}")