All Pairs

Sign up to mark as complete Sign up to bookmark this question
Asset Pricingx / 34
Behavioral Questionsx / 7
Brain Teasersx / 70
Derivatives Theoryx / 104
Digital Assets - Cryptox / 64
Energy Tradingx / 40
Linear Algebrax / 24
Math Questionsx / 26
Probability and Statistics Theoryx / 120
Programmingx / 34
Totalx / 524

Sign up to track your progress

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.
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.
Output
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)]
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)
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)}")
Title Category Subcategory Difficulty Status
All Vowels ProgrammingEasyEasy
Largest Possible Number ProgrammingEasyEasy
Missing Number ProgrammingEasyEasy
Smallest String ProgrammingEasyEasy
Word Frequency ProgrammingEasyEasy

Please log in to see the discussion.