Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’.
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.
[(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.
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]
- Python | Ways to create triplets from given list
- Python | Find maximum length sub-list in a nested list
- Find size of a list in Python
- Find average of a list in python
- Find Median of List in Python
- Python | Find Min/Max in heterogeneous list
- Python | Find missing elements in List
- Python - Find Minimum Pair Sum in list
- Python | Ways to find indices of value in list
- Python | Find most common element in a 2D list
- Python | Find all elements count in list
- Python | Ways to find length of list
- Python | Find indices with None values in given list
- Python | Find elements of a list by indices
- Python program to find Cumulative sum of a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : ManasChhabra2