Find the triplet that sum to a given value in Python

Get Prepinsta Prime

Get all 200+ courses offered by Prepinsta

Never Miss an OffCampus Update

Get OffCampus Updates on Social Media from PrepInsta

Follow us on our Media Handles, we post out OffCampus drives on our Instagram, Telegram, Discord, Whatsdapp etc.

Get Hiring Updates
Amazon,Google,Delottie & 30+companies are hiring ! Get hiring Updates right in your inbox from PrepInsta

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.

Get PrepInsta Prime Subscription

Get access to all the courses that PrepInsta offers, check the out below -

Companies

TCS, Cognizant, Delloite, Infosys, Wipro, CoCubes, KPMG, Amazone, ZS Associates, Accenture, Congnizant & other 50+ companies

Programming

Data Structures, Top 500 Codes, C, C++, Java Python & other 10+ subjects

Skills

Full Stack Web Development, Data Science, Machine Learning, AWS Cloud, & other 10+ skills and 20+ projects

OffCampus Updates

Never Miss OffCampus Updates

Get OffCampus Update from PrepInsta

Follow us on our Social Media Handles

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. 

Input: array = {1, 2, 3, 4, 5}, sum = 9

Output: 5, 3, 1

Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9.

triplet that sum to given value in python

Algorithm :

  • Take  size of the array from the user and store it in a variable say n.
  • Now take n elements of the array from the user.

Algorithm for function Find

  • Create three nested loop first loop runs from start to end (loop counter i), the second loop runs from i+1 to end (loop counter j) and the third loop runs from j+1 to end (loop counter k)
  • The counter of these loops represents the index of 3 elements of the triplets.
  • Find the sum of the ith, jth and kth element. If the sum is equal to a given sum. Print the triplet
triplet that sum to given value using python

Python Code

Run
def find(a, n, summ):
    print("Triplets are: ")
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if (a[i] + a[j] + a[k]) == summ:
                    print(a[i], a[j], a[k])


array = [1, 3, 5, 11, 8]
summ = 15

find(array, len(array), summ)

Output

Triplets are:
1 3 11

Comments