Python program to find all possible pairs with given sum
Given a list of integers and an integer variable K, write a Python program to find all pairs in the list with given sum K. Examples:
Input : lst =[1, 5, 3, 7, 9] K = 12 Output : [(5, 7), (3, 9)] Input : lst = [2, 1, 5, 7, -1, 4] K = 6 Output : [(2, 4), (1, 5), (7, -1)]
Method #1: Pythonic Naive This is a naive approach to the above problem. First, we take an empty list ‘res’ and start a loop and traverse each element of the given list of integers. In each iteration, pop the element, store it in ‘num’, find remaining difference for sum K, and check if the difference exists in the given list or not.
Python3
# Python3 program to find all pairs in # a list of integers with given sum def findPairs(lst, K): res = [] while lst: num = lst.pop() diff = K - num if diff in lst: res.append((diff, num)) res.reverse() return res # Driver code lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 print (findPairs(lst, K)) |
[(5, 7), (3, 9)]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
Method #2 : Using collections.Counter This approach follows the same method as discussed above using collections.Counter.
Python3
# Python3 program to find all pairs in # a list of integers with given sum from collections import Counter def findPairs(lst, K): res = [] count = Counter(lst) for x in lst: y = K - x if (x ! = y and count[y]) or (x = = y and count[y] > 1 ): res.append((x, y)) count.subtract((x, y)) return res # Driver code lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 print (findPairs(lst, K)) |
[(5, 7), (3, 9)]
Method #3 : itertools.combinations (Naive method) This is a naive approach to use itertools.combinations. We use a for loop to traverse through each combination and find out the desired one.
Python3
# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): res = [] for var in combinations(lst, 2 ): if var[ 0 ] + var[ 1 ] = = K: res.append((var[ 0 ], var[ 1 ])) return res # Driver code lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 print (findPairs(lst, K)) |
[(5, 7), (3, 9)]
Method #4 : itertools.combinations (Efficient method)
Python3
# Python3 program to find all pairs in # a list of integers with given sum from itertools import combinations def findPairs(lst, K): return [pair for pair in combinations(lst, 2 ) if sum (pair) = = K] # Driver code lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 print (findPairs(lst, K)) |
[(5, 7), (3, 9)]
Method#5: Using nested loops
Approach
this approach is a brute-force approach that uses nested loops to iterate through each element in the list and find all possible pairs that add up to the given sum. For each element in the list, the algorithm checks all the remaining elements in the list to find a pair whose sum is equal to the given sum. If a pair is found, it is added to the output list.
Algorithm
1. Initialize an empty list “result”.
2. Iterate through each element in the list “lst” and for each element, iterate through the remaining elements in the list.
3. If the sum of the two elements is equal to the given sum “K”, append the tuple of the two elements to the “result” list.
4. Return the “result” list.
Python3
def find_pairs(lst, K): result = [] for i in range ( len (lst)): for j in range (i + 1 , len (lst)): if lst[i] + lst[j] = = K: result.append((lst[i], lst[j])) return result lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 print (find_pairs(lst, K)) |
[(5, 7), (3, 9)]
Time complexity: O(n^2), where n is the size of the list
Space complexity: O(n), where n is the size of the list
METHOD 6: Using a set
APPROACH:
In this approach, we will use a set to keep track of the elements we have seen so far. For each element in the list, we will check if its complement (i.e., the difference between the given sum and the current element) is present in the set. If yes, we will add the pair to the result.
ALGORITHM:
1. Initialize an empty result list and an empty set called “seen”.
2. Iterate over each element “num” in the given list “lst”.
3. Calculate the complement “complement” of “num” by subtracting it from the target sum “K”.
4. Check if “complement” is present in the “seen” set.
5. If yes, add the pair (num, complement) to the result list.
6. Add “num” to the “seen” set.
7. Return the result list.
Python3
lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 result = [] seen = set () for num in lst: complement = K - num if complement in seen: result.append((num, complement)) seen.add(num) print (result) |
[(7, 5), (9, 3)]
Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the given list. This is because we iterate over each element in the list once and perform constant time operations (such as set lookup and list append) for each element.
Space Complexity:
The space complexity of this algorithm is O(n), where n is the length of the given list. This is because we store the elements seen so far in a set and the result pairs in a list, both of which can have a maximum size of n.
METHOD 7:Using Sorting and Two Pointers
APPROACH:
The given program finds all possible pairs from a given list of numbers that add up to a given target value. It uses the two-pointer technique, where two pointers traverse the sorted list from left and right simultaneously. By comparing the sum of the elements pointed by the left and right pointers with the target value, the pointers move inward until they meet or the sum is greater than the target value.
ALGORITHM:
1. Initialize an empty list called pairs to store the result.
2. Sort the given list of numbers.
3. Initialize two pointers, left and right, pointing to the start and end of the list respectively.
4. While the left pointer is less than the right pointer, do the following:
a. If the sum of the elements pointed by the left and right pointers is equal to the target value K, then add the pair to the list pairs and move the left and right pointers inward.
b. If the sum of the elements pointed by the left and right pointers is less than the target value K, then move the left pointer inward.
c. If the sum of the elements pointed by the left and right pointers is greater than the target value K, then move the right pointer inward.
5. Print the list pairs.
Python3
lst = [ 1 , 5 , 3 , 7 , 9 ] K = 12 pairs = [] lst.sort() left = 0 right = len (lst) - 1 while left < right: if lst[left] + lst[right] = = K: pairs.append((lst[left], lst[right])) left + = 1 right - = 1 elif lst[left] + lst[right] < K: left + = 1 else : right - = 1 print (pairs) |
[(3, 9), (5, 7)]
Time Complexity:
The time complexity of this program is O(n log n), where n is the length of the given list. The sorting of the list takes O(n log n) time. The two-pointer traversal takes O(n) time. Therefore, the overall time complexity is dominated by the sorting operation.
Space Complexity:
The space complexity of this program is O(1), as it uses only a constant amount of extra space to store the pointers and the result list.