Open In App

Print all triplets with given sum

Last Updated : 03 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of distinct elements. The task is to find triplets in array whose sum is equal to a given number.

Examples: 

Input: arr[] = {0, -1, 2, -3, 1}
        sum = -2
Output:  0 -3  1
        -1  2 -3
If we calculate the sum of the output,
0 + (-3) + 1 = -2
(-1) + 2 + (-3) = -2

Input: arr[] = {1, -2, 1, 0, 5}
       sum = 0
Output: 1 -2  1
If we calculate the sum of the output,
1 + (-2) + 1 = 0

Method 1: Brute Force.

Approach: The brute force approach in these type of questions aim to check all possible triplets present in the array. The triplet with sum=Target sum will be the answer. Now the question that arises is how should one check all possible triplets. To check all possible duplets fix a pointer on one element and for every such element traverse the array and check the sum. This will be the sum of all possible duplets

Likewise for checking all possible triplets one can fix two-pointers and move the third pointer over the array and as soon as it reaches the end of array increment the second pointer and again repeat the same. 

Algorithm:  

  1. Take three pointers i, j, k.
  2. Initialize i with zero and start a nested loop for i.
  3. Initialize j with (i+1) and start a nested loop for j.
  4. Initialize k with (j+1) and start a loop for k.
  5. If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k].
  6. Else keep incrementing k till it is equal to last index.
  7. Goto step 2 and increment j and for every value of j run the inner loop of k.
  8. If j is equal to 2nd last index Goto step 1 and increment the value of i till 3rd last index and again continue the whole process till the value of i is equal to the last index.  

Implementation:

C++




// A simple C++ program to find three elements
// whose sum is equal to given sum
#include <bits/stdc++.h>
using namespace std;
 
// Prints all triplets in arr[] with given sum
void findTriplets(int arr[], int n, int sum)
{
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {
                if (arr[i] + arr[j] + arr[k] == sum) {
                    cout << arr[i] << " "
                         << arr[j] << " "
                         << arr[k] << endl;
                }
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 0, -1, 2, -3, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findTriplets(arr, n, -2);
    return 0;
}


Java




// A simple Java program
// to find three elements
// whose sum is equal to
// given sum
import java.io.*;
 
class GFG {
 
    // Prints all triplets in
    // arr[] with given sum
    static void findTriplets(int arr[],
                             int n, int sum)
    {
        for (int i = 0;
             i < n - 2; i++) {
            for (int j = i + 1;
                 j < n - 1; j++) {
                for (int k = j + 1;
                     k < n; k++) {
                    if (arr[i] + arr[j] + arr[k] == sum) {
                        System.out.println(
                            arr[i] + " " + arr[j]
                            + " " + arr[k]);
                    }
                }
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 0, -1, 2, -3, 1 };
        int n = arr.length;
        findTriplets(arr, n, -2);
    }
}
 
// This code is contributed by m_kit


Python3




# A simple Python 3 program
# to find three elements
# whose sum is equal to
# given sum
 
# Prints all triplets in
# arr[] with given sum
def findTriplets(arr, n, sum):
 
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if (arr[i] + arr[j] +
                    arr[k] == sum):
                    print(arr[i], " ",
                          arr[j], " ",
                          arr[k], sep = "")
             
# Driver code
arr = [ 0, -1, 2, -3, 1 ]
n = len(arr)
findTriplets(arr, n, -2)
 
# This code is contributed
# by Smitha


C#




// A simple C# program
// to find three elements
// whose sum is equal to
// given sum
using System;
 
class GFG {
 
    // Prints all triplets in
    // arr[] with given sum
    static void findTriplets(int[] arr,
                             int n, int sum)
    {
        for (int i = 0;
             i < n - 2; i++) {
            for (int j = i + 1;
                 j < n - 1; j++) {
                for (int k = j + 1;
                     k < n; k++) {
                    if (arr[i] + arr[j] + arr[k] == sum) {
                        Console.WriteLine(
                            arr[i] + " " + arr[j]
                            + " " + arr[k]);
                    }
                }
            }
        }
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 0, -1, 2, -3, 1 };
        int n = arr.Length;
        findTriplets(arr, n, -2);
    }
}
// This code is contributed by akt_mit


PHP




<?php
// A simple PHP program to
// find three elements whose
// sum is equal to given sum
 
// Prints all triplets in
// arr[] with given sum
function findTriplets($arr, $n, $sum)
{
    for ($i = 0; $i < $n - 2; $i++)
    {
        for ($j = $i + 1; $j < $n - 1; $j++)
        {
            for ($k = $j + 1; $k < $n; $k++)
            {
                if ($arr[$i] + $arr[$j] +
                    $arr[$k] == $sum)
                {
                    echo $arr[$i], " ",
                         $arr[$j], " ",
                         $arr[$k], "\n";
                }
            }
        }
    }
}
 
// Driver code
$arr = array (0, -1, 2, -3, 1);
$n = sizeof($arr);
findTriplets($arr, $n, -2);
 
// This code is contributed by aj_36
?>


Javascript




<script>
 
// A simple Javascript program to find three elements
// whose sum is equal to given sum
 
// Prints all triplets in arr[] with given sum
function findTriplets(arr, n, sum)
{
    for (let i = 0; i < n - 2; i++) {
        for (let j = i + 1; j < n - 1; j++) {
            for (let k = j + 1; k < n; k++) {
                if (arr[i] + arr[j] + arr[k] == sum) {
                    document.write(arr[i]+ " "
                        + arr[j] + " "
                        + arr[k] + "<br>");
                }
            }
        }
    }
}
 
// Driver code
 
    let arr = [ 0, -1, 2, -3, 1 ];
    let n = arr.length;
    findTriplets(arr, n, -2);
 
// This code is contributed by Mayank Tyagi
 
</script>


Output

0 -3 1
-1 2 -3

Complexity Analysis: 

  • Time Complexity: O(n3). 
    As three nested for loops have been used.
  • Auxiliary Space: O(1). 
    As no data structure has been used for storing values.

Method 2: Hashing. 

Approach: 
Hashing can be used to solve this problem. HashTable or HashMaps allows us to perform lookup or search operations in constant time complexity. If one can find that for every possible duplet there is an element already existing in the array which can make sum=target sum then the problem will be solved in an efficient manner.
To implement Hashing, we can use unordered_set in C++ or HashSet in Java

  • As we fix first pointer(say a), traverse the array using second pointer(say b) and keep storing the elements encountered in a HashTable.
  • As soon as we find that the element which is equal to remaining sum (Target sum -(a+b)) that is already present in the HashTable, we print our triplet.

Algorithm:  

  1. Start the outer loop from i=0 till the (n-3)th index.
  2. For every iteration make an unordered set and enter the inner loop.
  3. Start the inner loop[ from j = (i+1)(as the values with which we have already checked will not appear in a valid triplet) till last index.
  4. Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed.
  5. Else push the value in the set as for later reference.
  6. Increment i and Goto step 2.

Pseudo Code:  

Run a loop from i=0 to n-3
  Create an empty hash table
  Run inner loop from j=i+1 to n-1
      If -(arr[i] + arr[j]) is present in hash table
         print arr[i], arr[j] and -(arr[i] + arr[j])
      Else
         Insert arr[j] in hash table.

Implementation:

C++




// C++ program to find triplets in a given
// array whose sum is equal to given sum.
#include <bits/stdc++.h>
using namespace std;
 
// function to print triplets with given sum
void findTriplets(int arr[], int n, int sum)
{
    for (int i = 0; i < n - 2; i++) {
        // Find all pairs with sum equals to
        // "sum-arr[i]"
        unordered_set<int> s;
        for (int j = i + 1; j < n; j++) {
            int x = sum - (arr[i] + arr[j]);
            if (s.find(x) != s.end())
                printf("%d %d %d\n", x, arr[i], arr[j]);
            else
                s.insert(arr[j]);
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 0, -1, 2, -3, 1 };
    int sum = -2;
    int n = sizeof(arr) / sizeof(arr[0]);
    findTriplets(arr, n, sum);
    return 0;
}


Java




// Java program to find triplets in a given
// array whose sum is equal to given sum.
import java.util.*;
 
class GFG {
 
    // function to print triplets with given sum
    static void findTriplets(int arr[], int n, int sum)
    {
        for (int i = 0; i < n - 2; i++) {
            // Find all pairs with sum equals to
            // "sum-arr[i]"
            HashSet<Integer> s = new HashSet<>();
            for (int j = i + 1; j < n; j++) {
                int x = sum - (arr[i] + arr[j]);
                if (s.contains(x))
                    System.out.printf(
                        "%d %d %d\n", x, arr[i], arr[j]);
                else
                    s.add(arr[j]);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 0, -1, 2, -3, 1 };
        int sum = -2;
        int n = arr.length;
        findTriplets(arr, n, sum);
    }
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 program to find triplets in a given
# array whose Sum is equal to given sum.
import math as mt
 
# function to print triplets with given sum
def findTriplets(arr, n, Sum):
 
    for i in range(n - 2):
         
        # Find all pairs with Sum equals
        # to "Sum-arr[i]"
        s = dict()
        for j in range(i + 1, n):
            x = Sum - (arr[i] + arr[j])
            if x in s.keys():
                print(x, arr[i], arr[j])
            else:
                s[arr[j]] = 1
         
# Driver code
arr = [ 0, -1, 2, -3, 1 ]
Sum = -2
n = len(arr)
findTriplets(arr, n, Sum)
 
# This code is contributed
# by mohit kumar 29


C#




// C# program to find triplets in a given
// array whose sum is equal to given sum.
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // function to print triplets with given sum
    static void findTriplets(int[] arr, int n, int sum)
    {
        for (int i = 0; i < n - 2; i++) {
            // Find all pairs with sum equals to
            // "sum-arr[i]"
            HashSet<int> s = new HashSet<int>();
            for (int j = i + 1; j < n; j++) {
                int x = sum - (arr[i] + arr[j]);
                if (s.Contains(x))
                    Console.Write("{0} {1} {2}\n", x, arr[i], arr[j]);
                else
                    s.Add(arr[j]);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 0, -1, 2, -3, 1 };
        int sum = -2;
        int n = arr.Length;
        findTriplets(arr, n, sum);
    }
}
// This code is contributed by Princi Singh


Javascript




<script>
// Javascript program to find triplets in a given
// array whose sum is equal to given sum.
     
    // function to print triplets with given sum
    function findTriplets(arr,n,sum)
    {
        for (let i = 0; i < n - 2; i++) {
            // Find all pairs with sum equals to
            // "sum-arr[i]"
            let s = new Set();
            for (let j = i + 1; j < n; j++) {
                let x = sum - (arr[i] + arr[j]);
                if (s.has(x))
                    document.write( x+" "+ arr[i]+" "+ arr[j]+"<br>");
                else
                    s.add(arr[j]);
            }
        }
    }
     
    // Driver code
    let arr=[0, -1, 2, -3, 1];
    let sum = -2;
    let n = arr.length;
    findTriplets(arr, n, sum);
     
     
// This code is contributed by unknown2108
</script>


Output

-3 0 1
2 -1 -3

Complexity Analysis:  

  • Time Complexity: O(n2). 
    Use of a nested for loop brings the time complexity to n2.
  • Auxiliary Space: O(n). 
    As an unordered_set data structure has been used for storing values.

Method 3: This method uses the method of Sorting and Two-pointer Technique to solve the above problem. This execution will involve O(n2)) time complexity and O(1) space complexity. The idea is based on Method 2 of this post.

Approach : The two pointer technique can be brought into action using the sorting technique. In two pointer technique one can search for the pair having a target sum in linear time. The idea here is to fix one pointer (say a) and use the remaining pointers to find the pair having required sum Target-value at(a) efficiently. 
Now let’s discuss how we can find the required pair effectively using two pointer technique. The pointers used for two pointer technique are say (l and r)

  • So if the sum = value(a) + value(l) + value(r) exceeds the required sum, for same (a, l) the required value(r) should be less than the previous. Thus, decrementing the r pointer. 
  • If the sum = value(a) + value(l) + value(r) is less than the required sum, for same (a, r) the required value(l) should be greater than the previous. Thus, incrementing the l pointer.

Algorithm:  

  1. Sort the array and for every element arr[i] search for the other two elements arr[l], arr[r] such that arr[i]+arr[l]+arr[r]=Target sum.
  2. Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted.
  3. Run an outer loop taking control variable as i and for every iteration initialize a value l which is the first pointer with i+1 and r with last index.
  4. Now enter into a while loop which will run till the value of l<r.
  5. If arr[i]+arr[l]+arr[r]>Target sum then decrement r by 1 as the required sum is less than the current sum and decreasing the value of will do the needful.
  6. If arr[i]+arr[l]+arr[r]<Target sum then increment l by 1 as the required sum is less than the current sum and increasing the value of will do the needful.
  7. If arr[i]+arr[l]+arr[r]==Target sum print the values.
  8. Increment i Goto Step 3.

Pseudo Code :  

1. Sort all element of array
2. Run loop from i=0 to n-2.
     Initialize two index variables l=i+1 and r=n-1
4. while (l < r) 
     Check sum of arr[i], arr[l], arr[r] is
     given sum or not if sum is 'sum', then print 
     the triplet and do l++ and r--.
5. If sum is less than given sum then l++
6. If sum is greater than given sum then r--
7. If not exist in array then print not found.

Implementation:

C++




// C++ program to find triplets in a given
// array whose sum is given sum.
#include <bits/stdc++.h>
using namespace std;
 
// Function to print triplets with given sum
    vector<vector<int>> findTriplets(int nums[],int n,int sumTarget) {
        vector<vector<int>> res;       
        if(n <=2) return res;
         
        sort(nums,nums + n);
         
        for(int i=0;i<n;i++){
             
           if(i>0 && nums[i] == nums[i-1])  // avoid duplicate triplets count
                continue;
             
            int num = nums[i];
            int target = sumTarget - num;
             
            for(int l=i+1, r=n-1; l<r; ) {
                 
                if(nums[l]+nums[r] > target)                    
                    r--;
                 
                else if (nums[l]+nums[r] < target)
                    l++;
                 
                else {
                    // nums[l] + nums[r] == target
                    res.push_back({nums[i], nums[l], nums[r]});
 
                    // skip duplicates
                    while( l<n-1 && nums[l]==nums[l+1]) l++;
                    while( r>0 && nums[r]==nums[r-1]) r--;
                                             
                    l++;
                    r--;                   
                     
                }
                 
            }                                 
             
        }
        return res;          
    }
// Driver code
int main()
{
    int arr[] = { 0, -1, 2, -3, 1, -1, 3, 0};
    int sum = -2;
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<vector<int>> res = findTriplets(arr, n, sum);
    cout<<"Unique triplets found are : \n";
    for(int i = 0;i<res.size();i++)
      cout<<res[i][0]<<" "<<res[i][1]<<" "<<res[i][2]<<"\n";
   
    return 0;
}


Java




// Java program to find triplets
// in a given array whose sum
// is given sum.
import java.io.*;
import java.util.*;
 
class GFG {
 
    // function to print
    // triplets with given sum
    static void findTriplets(int[] arr,
                             int n, int sum)
    {
        // sort array elements
        Arrays.sort(arr);
 
        for (int i = 0;
             i < n - 1; i++) {
            // initialize left and right
            int l = i + 1;
            int r = n - 1;
            int x = arr[i];
            while (l < r) {
                if (x + arr[l] + arr[r] == sum) {
                    // print elements if it's
                    // sum is given sum.
                    System.out.println(
                        x + " " + arr[l] + " "
                        + arr[r]);
                    l++;
                    r--;
                }
 
                // If sum of three elements
                // is less than 'sum' then
                // increment in left
                else if (x + arr[l] + arr[r] < sum)
                    l++;
 
                // if sum is greater than
                // given sum, then decrement
                // in right side
                else
                    r--;
            }
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int[] arr = new int[] { 0, -1, 2, -3, 1 };
        int sum = -2;
        int n = arr.length;
        findTriplets(arr, n, sum);
    }
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Python3




# Python3 program to find triplets in a
# given array whose sum is given sum.
 
# function to print triplets with
# given sum
def findTriplets(arr, n, sum):
 
    # sort array elements
    arr.sort();
 
    for i in range(0, n - 1):
         
        # initialize left and right
        l = i + 1;
        r = n - 1;
        x = arr[i];
        while (l < r) :
            if (x + arr[l] + arr[r] == sum) :
                 
                # print elements if it's sum
                # is given sum.
                print(x, arr[l], arr[r]);
                l = l + 1;
                r = r - 1;
             
            # If sum of three elements is less
            # than 'sum' then increment in left
            elif (x + arr[l] + arr[r] < sum):
                l = l + 1;
 
            # if sum is greater than given sum,
            # then decrement in right side
            else:
                r = r - 1;
         
# Driver code
arr = [ 0, -1, 2, -3, 1 ];
sum = -2;
n = len(arr);
findTriplets(arr, n, sum);
 
# This code is contributed by
# Shivi_Aggarwal


C#




// C# program to find triplets
// in a given array whose sum
// is given sum.
using System;
 
class GFG {
 
    // function to print
    // triplets with given sum
    static void findTriplets(int[] arr,
                             int n, int sum)
    {
        // sort array elements
        Array.Sort(arr);
 
        for (int i = 0; i < n - 1; i++) {
            // initialize left and right
            int l = i + 1;
            int r = n - 1;
            int x = arr[i];
            while (l < r) {
                if (x + arr[l] + arr[r] == sum) {
                    // print elements if it's
                    // sum is given sum.
                    Console.WriteLine(x + " " + arr[l] + " " + arr[r]);
                    l++;
                    r--;
                }
 
                // If sum of three elements
                // is less than 'sum' then
                // increment in left
                else if (x + arr[l] + arr[r] < sum)
                    l++;
 
                // if sum is greater than
                // given sum, then decrement
                // in right side
                else
                    r--;
            }
        }
    }
 
    // Driver code
    static int Main()
    {
        int[] arr = new int[] { 0, -1, 2, -3, 1 };
        int sum = -2;
        int n = arr.Length;
        findTriplets(arr, n, sum);
        return 0;
    }
}
 
// This code is contributed by rahul


PHP




<?php
// PHP program to find triplets
// in a given array whose sum
// is given sum.
 
// function to print triplets
// with given sum
function findTriplets($arr, $n, $sum)
{
    // sort array elements
    sort($arr);
 
    for ($i = 0; $i < $n - 1; $i++)
    {
        // initialize left and right
        $l = $i + 1;
        $r = $n - 1;
        $x = $arr[$i];
        while ($l < $r)
        {
            if ($x + $arr[$l] +
                $arr[$r] == $sum)
            {
                // print elements if it's
                // sum is given sum.
                echo $x, " ", $arr[$l],
                         " ", $arr[$r], "\n";
                $l++;
                $r--;
            }
 
            // If sum of three elements
            // is less than 'sum' then
            // increment in left
            else if ($x + $arr[$l] +
                     $arr[$r] < $sum)
                $l++;
 
            // if sum is greater
            // than given sum, then
            // decrement in right side
            else
                $r--;
        }
    }
}
 
// Driver code
$arr = array(0, -1, 2, -3, 1);
$sum = -2;
$n = sizeof($arr);
findTriplets($arr, $n, $sum);
 
// This code is contributed by ajit
?>


Javascript




<script>
    // Javascript program to find triplets
    // in a given array whose sum
    // is given sum.
     
    // function to print
    // triplets with given sum
    function findTriplets(arr, n, sum)
    {
     
        // sort array elements
        arr.sort(function(a, b){return a - b});
  
        for (let i = 0; i < n - 1; i++) {
            // initialize left and right
            let l = i + 1;
            let r = n - 1;
            let x = arr[i];
            while (l < r) {
                if (x + arr[l] + arr[r] == sum)
                {
                 
                    // print elements if it's
                    // sum is given sum.
                    document.write(x + " " + arr[l] + " " + arr[r] + "</br>");
                    l++;
                    r--;
                }
  
                // If sum of three elements
                // is less than 'sum' then
                // increment in left
                else if (x + arr[l] + arr[r] < sum)
                    l++;
  
                // if sum is greater than
                // given sum, then decrement
                // in right side
                else
                    r--;
            }
        }
    }
     
    let arr = [ 0, -1, 2, -3, 1 ];
    let sum = -2;
    let n = arr.length;
    findTriplets(arr, n, sum);
  
 // This code is contributed by rameshtravel07.
</script>


Output

Unique triplets found are : 
-3 -1 2
-3 0 1
-1 -1 0

Complexity Analysis: 

  • Time Complexity: O(n2)
    Use of a nested loop (one for iterating, other for two-pointer technique) brings the time complexity to O(n2).
  • Auxiliary Space: O(1). 
    As no use of additional data structure is used.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads