Sign up to mark as complete
Sign up to bookmark this question
All Pairs
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.
Inputs
The inputs are defined as follows:
Return a list of tuples, where each tuple contains a pair of integers that sum up to the target integer.
Example Tests
def find_pairs_with_sum(arr: List[int], target: int) -> List[Tuple[int, int]]:
pass
Inputs
The inputs are defined as follows:
- arr: A list of integers containing both positive and negative numbers. The array may have duplicate values.
- target: An integer that we are interested in finding pairs for.
Return a list of tuples, where each tuple contains a pair of integers that sum up to the target integer.
Example Tests
- find_pairs_with_sum([3, 4, 2, 5], 7) should return [(3, 4), (2, 5)]
- find_pairs_with_sum([2, 4, 1, 5], 9) should return [(4, 5)]
- find_pairs_with_sum([7, 1, 2, 3, 4, -2], 5) should return [(1, 4), (2, 3), (7, -2)]
Hint
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)
Solution
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)}")
Related Questions
Title | Category | Subcategory | Difficulty | Status |
---|---|---|---|---|
All Vowels | Programming | Easy | Easy | |
Largest Possible Number | Programming | Easy | Easy | |
Missing Number | Programming | Easy | Easy | |
Smallest String | Programming | Easy | Easy | |
Word Frequency | Programming | Easy | Easy |
Discussion
Please log in to see the discussion.