Print all triplets with given sum

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. Intialize i with zero and start a nested loop for i.
  3. Intialize 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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


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-2)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-2
  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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 - 1; 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 - 1; 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 - 1):
          
        # 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 - 1; 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

chevron_right


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 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 contol 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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
void findTriplets(int arr[], int n, int sum)
{
    // Sort array elements
    sort(arr, arr + n);
  
    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.
                printf("%d %d %d\n", 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
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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right


Output:

-3 -1 2
-3 0 1

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.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.