Triplet sum in python assignment expert

Triplet Sum

Given an array n integers, find and print all the unique triplets [a, b, c] in the array which give the sum K. [a+b+c=K].Input

The first line of the input will be space separated integers, denoting the elements of the array. The second line of the input will be an integer denoting the required sum KOutput

The output should be multiple lines, each line containing a unique triplet. The elements of the triple must be sorted in increasing order and all the triplets printed must be sorted in increasing order. Print "No Matching Triplets Found" if there are no triplets with the given sum.Explanation

When the given array is [0, 1, 2, 3, 5, 7, 13, 17, 19, 19] and the required sum is 22, the triplets [0, 3, 19], [0, 5, 17], [1, 2, 19], [2, 3, 17] and [2, 7, 13] have the given sum 22.

Sample Input 1

0 12 17 8 9 21

29

Sample Output 1

[0, 8, 21]

[0, 12, 17]

[8, 9, 12]

Sample Input 2

0 1 2 3 5 7 13 17 19 19

22

Sample Output 2

[0, 3, 19]

[0, 5, 17]

[1, 2, 19]

[2, 3, 17]

[2, 7, 13]

Triplet Sum

Given an array n integers, find and print all the unique triplets [a, b, c] in the array which give the sum K. [a+b+c=K].Input

The first line of the input will be space separated integers, denoting the elements of the array. The second line of the input will be an integer denoting the required sum KOutput

The output should be multiple lines, each line containing a unique triplet. The elements of the triple must be sorted in increasing order and all the triplets printed must be sorted in increasing order. Print "No Matching Triplets Found" if there are no triplets with the given sum.Explanation

Sample Input 1

0 12 17 8 9 21

29

Sample Output 1

[0, 8, 21]

[0, 12, 17]

[8, 9, 12]

Sample Input 2

0 1 2 3 5 7 13 17 19 19

22

Sample Output 2

[0, 3, 19]

[0, 5, 17]

[1, 2, 19]

[2, 3, 17]

[2, 7, 13]

The output should be printed exactly as shown in the above test cases.

# Program to find a triplet returns true if there is triplet
# with sum of a, b, c equal to 'K' present in arr[].
def TripletSum[arr, K]:
    arr_size = len[arr]
    found=False
    arr.sort[]
 
    for a in range[0, arr_size - 2]:    
        b = a + 1
        c = arr_size - 1
        while [b < c]:        
            if[ arr[a] + arr[b] + arr[c] == K]:
                print[[ arr[a], arr[b], arr[c]]]
                b+=1
                c-=1
                found = True          
            elif [arr[a] + arr[b] + arr[c] < K]:
                b += 1
            else:
                c -= 1
    if [found == False]:
        print["No Matching Triplets Found"]
 
 
# TEST
arr = [0, 1, 2, 3, 5, 7, 13, 17, 19, 19]
K = 22
TripletSum[arr, K]

# OUTPUT
[0, 3, 19]
[0, 5, 17]
[1, 2, 19]
[2, 3, 17]
[2, 7, 13]

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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 is a triplet [12, 3 and 9] present 
    in the array whose sum is 24. 
    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.

    Method 1: This is the naive approach towards solving the above problem.  

    • Approach: A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops.
    • Algorithm: 
      1. Given an array of length n and a sum s
      2. Create three nested loop first loop runs from start to end [loop counter i], second loop runs from i+1 to end [loop counter j] and third loop runs from j+1 to end [loop counter k]
      3. The counter of these loops represents the index of 3 elements of the triplets.
      4. Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
      5. If there is no triplet, then print that no triplet exist.
    • Implementation:

    C++

    #include

    using namespace std;

    bool find3Numbers[int A[], int arr_size, int sum]

    {

        for [int i = 0; i < arr_size - 2; i++]

        {

            for [int j = i + 1; j < arr_size - 1; j++]

            {

                for [int k = j + 1; k < arr_size; k++]

                {

                    if [A[i] + A[j] + A[k] == sum]

                    {

                        cout

    Javascript

    function find3Numbers[A, arr_size, sum]

    {

        let l, r;

        for [let i = 0; i < arr_size - 2; i++]

        {

            for [let j = i + 1; j < arr_size - 1; j++]

            {

                for [let k = j + 1; k < arr_size; k++]

                {

                    if [A[i] + A[j] + A[k] == sum]

                    {

                        document.write["Triplet is " + A[i] +

                            ", " + A[j] + ", " + A[k]];

                        return true;

                    }

                }

            }

        }

        return false;

    }

        let A = [ 1, 4, 45, 6, 10, 8 ];

        let sum = 22;

        let arr_size = A.length;

        find3Numbers[A, arr_size, sum];

    Output

    Triplet is 4, 10, 8

    • Complexity Analysis: 
      • Time Complexity: O[n3]. 
        There are three nested loops traversing the array, so the time complexity is O[n^3]
      • Space Complexity: O[1]. 
        As no extra space is required.

    Method 2: This method uses sorting to increase the efficiency of the code. 

    • Approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop.
    • Algorithm : 
      1. Sort the given array.
      2. Loop over the array and fix the first element of the possible triplet, arr[i].
      3. Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, 
        1. If the sum is smaller than the required sum, increment the first pointer.
        2. Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
        3. Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
    • Implementation:

    C++

    #include

    using namespace std;

    bool find3Numbers[int A[], int arr_size, int sum]

    {

        int l, r;

        sort[A, A + arr_size];

        for [int i = 0; i < arr_size - 2; i++] {

            l = i + 1;

            r = arr_size - 1;

            while [l < r] {

                if [A[i] + A[l] + A[r] == sum] {

                    printf["Triplet is %d, %d, %d", A[i], A[l],A[r]];

                    return true;

                }

                else if [A[i] + A[l] + A[r] < sum]

                    l++;

                else

                    r--;

            }

        }

        return false;

    }

    int main[]

    {

        int A[] = { 1, 4, 45, 6, 10, 8 };

        int sum = 22;

        int arr_size = sizeof[A] / sizeof[A[0]];

        find3Numbers[A, arr_size, sum];

        return 0;

    }

    C

    #include

    #include

    #include

    int cmpfunc[const void* a, const void* b]

    {

        return [*[int*]a - *[int*]b];

    }

    bool find3Numbers[int A[], int arr_size, int sum]

    {

        int l, r;

        qsort[A, arr_size, sizeof[int], cmpfunc];

        for [int i = 0; i < arr_size - 2; i++]

        {

            l = i + 1;

            r = arr_size - 1;

            while [l < r] {

                if [A[i] + A[l] + A[r] == sum] {

                    printf["Triplet is %d, %d, %d", A[i], A[l],

                           A[r]];

                    return true;

                }

                else if [A[i] + A[l] + A[r] < sum]

                    l++;

                else

                    r--;

            }

        }

        return false;

    }

    int main[]

    {

        int A[] = { 1, 4, 45, 6, 10, 8 };

        int sum = 22;

        int arr_size = sizeof[A] / sizeof[A[0]];

        find3Numbers[A, arr_size, sum];

        return 0;

    }

    Java

    class FindTriplet {

        boolean find3Numbers[int A[], int arr_size, int sum]

        {

            int l, r;

            quickSort[A, 0, arr_size - 1];

            for [int i = 0; i < arr_size - 2; i++] {

                l = i + 1;

                r = arr_size - 1;

                while [l < r] {

                    if [A[i] + A[l] + A[r] == sum] {

                        System.out.print["Triplet is " + A[i] + ", " + A[l] + ", " + A[r]];

                        return true;

                    }

                    else if [A[i] + A[l] + A[r] < sum]

                        l++;

                    else

                        r--;

                }

            }

            return false;

        }

        int partition[int A[], int si, int ei]

        {

            int x = A[ei];

            int i = [si - 1];

            int j;

            for [j = si; j

    Javascript

    function find3Numbers[A, arr_size, sum]

    {

        let l, r;

        A.sort[[a,b] => a-b];

        for [let i = 0; i < arr_size - 2; i++] {

            l = i + 1;

            r = arr_size - 1;

            while [l < r] {

                if [A[i] + A[l] + A[r] == sum]

                {

                document.write["Triplet is " + A[i] + ", "

                      + A[l] + ", " + A[r]];

                    return true;

                }

                else if [A[i] + A[l] + A[r] < sum]

                    l++;

                else

                    r--;

            }

        }

        return false;

    }

        let A = [ 1, 4, 45, 6, 10, 8 ];

        let sum = 22;

        let arr_size = A.length;

        find3Numbers[A, arr_size, sum];

    Output

    Triplet is 4, 8, 10

    • Complexity Analysis: 
      • Time complexity: O[N^2]. 
        There are only two nested loops traversing the array, so time complexity is O[n^2]. Two pointers algorithm takes O[n] time and the first element can be fixed using another nested traversal.
      • Space Complexity: O[1]. 
        As no extra space is required.

    Method 3: This is a Hashing-based solution. 

    • Approach: This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet. 
       
    • Algorithm: 
      1. Traverse the array from start to end. [loop counter i]
      2. Create a HashMap or set to store unique pairs.
      3. Run another loop from i+1 to end of the array. [loop counter j]
      4. If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet [arr[i], arr[j], x-arr[i]-arr[j]] and break
      5. Insert the jth element in the set.
    • Implementation:

    C++

    #include

    using namespace std;

    bool find3Numbers[int A[], int arr_size, int sum]

    {

        for [int i = 0; i < arr_size - 2; i++]

        {

            unordered_set s;

            int curr_sum = sum - A[i];

            for [int j = i + 1; j < arr_size; j++]

            {

                if [s.find[curr_sum - A[j]] != s.end[]]

                {

                    printf["Triplet is %d, %d, %d", A[i],

                           A[j], curr_sum - A[j]];

                    return true;

                }

                s.insert[A[j]];

            }

        }

        return false;

    }

    int main[]

    {

        int A[] = { 1, 4, 45, 6, 10, 8 };

        int sum = 22;

        int arr_size = sizeof[A] / sizeof[A[0]];

        find3Numbers[A, arr_size, sum];

        return 0;

    }

    Java

    import java.util.*;

    class GFG {

        static boolean find3Numbers[int A[],

                                    int arr_size, int sum]

        {

            for [int i = 0; i < arr_size - 2; i++] {

                HashSet s = new HashSet[];

                int curr_sum = sum - A[i];

                for [int j = i + 1; j < arr_size; j++]

                {

                    if [s.contains[curr_sum - A[j]]]

                    {

                        System.out.printf["Triplet is %d,

                                            %d, %d", A[i],

                                          A[j], curr_sum - A[j]];

                        return true;

                    }

                    s.add[A[j]];

                }

            }

            return false;

        }

        public static void main[String[] args]

        {

            int A[] = { 1, 4, 45, 6, 10, 8 };

            int sum = 22;

            int arr_size = A.length;

            find3Numbers[A, arr_size, sum];

        }

    }

    Python3

    def find3Numbers[A, arr_size, sum]:

        for i in range[0, arr_size-1]:

            s = set[]

            curr_sum = sum - A[i]

            for j in range[i + 1, arr_size]:

                if [curr_sum - A[j]] in s:

                    print["Triplet is", A[i],

                            ", ", A[j], ", ", curr_sum-A[j]]

                    return True

                s.add[A[j]]

        return False

    A = [1, 4, 45, 6, 10, 8]

    sum = 22

    arr_size = len[A]

    find3Numbers[A, arr_size, sum]

    C#

    using System;

    using System.Collections.Generic;

    public class GFG {

        static bool find3Numbers[int[] A,

                                 int arr_size, int sum]

        {

            for [int i = 0; i < arr_size - 2; i++] {

                HashSet s = new HashSet[];

                int curr_sum = sum - A[i];

                for [int j = i + 1; j < arr_size; j++]

                {

                    if [s.Contains[curr_sum - A[j]]]

                    {

                        Console.Write["Triplet is {0}, {1}, {2}", A[i],

                                      A[j], curr_sum - A[j]];

                        return true;

                    }

                    s.Add[A[j]];

                }

            }

            return false;

        }

        public static void Main[]

        {

            int[] A = { 1, 4, 45, 6, 10, 8 };

            int sum = 22;

            int arr_size = A.Length;

            find3Numbers[A, arr_size, sum];

        }

    }

    Javascript

        function find3Numbers[A,arr_size,sum]

        {

            for [let i = 0; i < arr_size - 2; i++] {

                let s = new Set[];

                let curr_sum = sum - A[i];

                for [let j = i + 1; j < arr_size; j++]

                {

                    if [s.has[curr_sum - A[j]]]

                    {

                        document.write[

                        "Triplet is " +A[i]+", "+A[j]+", "+

                        [curr_sum - A[j]]+"
    "

                        ];

                        return true;

                    }

                    s.add[A[j]];

                }

            }

            return false;

        }

        let A=[1, 4, 45, 6, 10, 8];

        let sum = 22;

        let arr_size = A.length;

        find3Numbers[A, arr_size, sum];

    Output:

    Triplet is 4, 8, 10

    Time complexity: O[N^2] 
    Auxiliary Space: O[N], since n extra space has been taken.

    You can watch the explanation of the problem on YouTube discussed By Geeks For Geeks Team.

    You can also refer this video present on Youtube.
    How to print all triplets with given sum? 
    Refer Find all triplets with zero sum. 
    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


    How do you count triplets in Python?

    res := 0..
    for i in range 0 to size of nums - 1, do. for j in range i+1 to size of nums - 1, do. for k in range j+1 to size of nums - 1, do. if |nums[i] - nums[j]|

    Chủ Đề