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 browser
1# Program to check if any pair in list sums to target
2
3numbers = list(map(int, input("Enter integers separated by space: ").split()))
4target = int(input("Enter target sum: "))
5
6seen = set()
7found = False
8
9for x in numbers:
10 if target - x in seen:
11 found = True
12 break
13 seen.add(x)
14
15if 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.