Example Programming Assignments

  1. All pairs
  2. Longest Common Subsequence (LCS)
  3. Priority Queue using Heaps
  1. Easy
  2. Medium
  3. Hard
Click category to hide/unhide questions

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)]

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)

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)}")