Python | Find all triplets in a list with given sum
Last Updated :
17 Mar, 2023
Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’.
Examples:
Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10
Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]
Input : [12, 3, 6, 1, 6, 9], k = 24
Output : [(12, 6, 6), (12, 9, 3)]
Approach #1 : Naive (Using set) In this approach, we use two for loops. The first loop sets first element, another to check whether other two elements including first sums up to k or not. This approach takes O(n2) time complexity.
Python3
def findTriplets(lst, k):
triplet_count = 0
final_temp_list = []
for i in range ( 0 , len (lst) - 1 ):
s = set ()
temp_list = []
temp_list.append(lst[i])
curr_k = k - lst[i]
for j in range (i + 1 , len (lst)):
if (curr_k - lst[j]) in s:
triplet_count + = 1
temp_list.append(lst[j])
temp_list.append(curr_k - lst[j])
final_temp_list.append( tuple (temp_list))
temp_list.pop( 2 )
temp_list.pop( 1 )
s.add(lst[j])
return final_temp_list
lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
k = 10
print (findTriplets(lst, k))
|
Output:
[(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]
Approach #2 : Using itertools Python itertools module provide combination(iterable, r) function. This tool returns the r length subsequences of elements from the input iterable. Every time we make a combination of 3 elements and check if they sums up to k or not.
Python3
from itertools import combinations
def findTriplets(lst, key):
def valid(val):
return sum (val) = = key
return list ( filter (valid, list (combinations(lst, 3 ))))
lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
print (findTriplets(lst, 10 ))
|
Output:
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]
Approach#3: using while loop
This approach implements the classic algorithm for finding all triplets in an input list that sum up to a given value k. It first sorts the input list in ascending order, and then iterates through all possible triplets using three nested loops. For each triplet, it checks if the sum equals k and if so, appends the triplet to a results list. Finally, it returns the results list.
Algorithm
1. Sort the input list in non-decreasing order.
2. Initialize an empty result list.
3. Iterate through the input list from the first element to the second-to-last element.
4. For each element, initialize two pointers left and right, one pointing to the element next to it and the other pointing to the last element of the list.
5. While left is less than right:
a. If the sum of the current element, the element at index left, and the element at index right is equal to k, append a tuple of these three elements to the result list.
b. If the sum is less than k, increment left.
c. If the sum is greater than k, decrement right.
6. Return the result list.
Python3
def find_triplets(input_list, k):
input_list.sort()
result = []
for i in range ( len (input_list) - 2 ):
left = i + 1
right = len (input_list) - 1
while left < right:
if input_list[i] + input_list[left] + input_list[right] = = k:
result.append((input_list[i], input_list[left], input_list[right]))
left + = 1
right - = 1
elif input_list[i] + input_list[left] + input_list[right] < k:
left + = 1
else :
right - = 1
return result
input_list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
k = 10
print (find_triplets(input_list, k))
|
Output
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]
Time complexity: O(n^2), where n is the length of the input list. This is because the outer loop iterates through all possible triplets, and the inner loop performs a constant amount of work for each iteration of the outer loop.
Auxiliary Space: O(1), because the code only uses a constant amount of additional memory to store the left and right indices and the results list.
Similar Reads
Python3 Program to Find all triplets with zero sum
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1}Output : (0 -1 1), (2 -3 1)Explanation : The triplets with zero sum are0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5}Output : 1 -2 1Explan
6 min read
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
7 min read
Python | Ways to create triplets from given list
To create triplets from a given list, we aim to group consecutive elements into sublists of three. This process involves iterating through the list and extracting segments of three adjacent elements, resulting in a new list where each item is a triplet. Using list comprehensionList Comprehension in
4 min read
Python - Combinations of sum with tuples in tuple list
Sometimes, while working with data, we can have a problem in which we need to perform tuple addition among all the tuples in list. This can have applications in many domains. Letâs discuss certain ways in which this task can be performed. Method #1: Using combinations() + list comprehension This pro
4 min read
Python Program for Find a triplet from three linked lists with sum equal to a given number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "
4 min read
Sum all Items in Python List without using sum()
In Python, typically the sum() function is used to get the sum of all elements in a list. However, there may be situations where we are required to sum the elements without using the sum() function. Let's explore different methods to sum the items in a list manually. Using for loopUsing a for loop i
3 min read
Python | Triplet iteration in List
List iteration is common in programming, but sometimes one requires to print the elements in consecutive triplets. This particular problem is quite common and having a solution to it always turns out to be handy. Lets discuss certain way in which this problem can be solved. Method #1 : Using list co
6 min read
Python - Pairs with Sum equal to K in tuple list
Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be pe
6 min read
Python3 Program to Find a triplet that sum to a given value
Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false. Examples: Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There i
6 min read
Python program to find the group sum till each K in a list
Given a List, the task is to write a Python program to perform grouping of sum till K occurs. Examples: Input : test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1], K = 6 Output : [10, 6, 2, 6, 21, 6, 1] Explanation : 2 + 3 + 5 = 10, grouped and cumulated before 6. Input : test_list = [2, 3, 5, 6, 2, 6, 8
3 min read