Pair Sum Problem in Python
Check if there exists a pair of numbers in the list that adds up to a target sum.
IntermediateList ProgramsExample 23 of 25
pair-sum-problem.py
Run in browser1# Program to check if any pair in list sums to target23numbers = list(map(int, input("Enter integers separated by space: ").split()))4target = int(input("Enter target sum: "))56seen = set()7found = False89for x in numbers:10 if target - x in seen:11 found = True12 break13 seen.add(x)1415if found:16 print("Found a pair with the given sum.")17else:18 print("No pair with the given sum found.")
Output
Enter integers separated by space: 1 2 3 4 Enter target sum: 5 Found a pair with the given sum.
What's going on
We use a set to track seen numbers and check for the complement (target - x) in O(1) average time.