Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Find a triplet that sum to a given value

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like 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.

Recommended Practice
 

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 <bits/stdc++.h>
using namespace std;
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    // Fix the first element as A[i]
    for (int i = 0; i < arr_size - 2; i++)
    {
 
        // Fix the second element as A[j]
        for (int j = i + 1; j < arr_size - 1; j++)
        {
 
            // Now look for the third number
            for (int k = j + 1; k < arr_size; k++)
            {
                if (A[i] + A[j] + A[k] == sum)
                {
                    cout << "Triplet is " << A[i] <<
                        ", " << A[j] << ", " << A[k];
                    return true;
                }
            }
        }
    }
 
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver code */
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;
}
 
// This is code is contributed by rathbhupendra

C




#include <stdio.h>
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    int l, r;
 
    // Fix the first element as A[i]
    for (int i = 0; i < arr_size - 2; i++) {
 
        // Fix the second element as A[j]
        for (int j = i + 1; j < arr_size - 1; j++) {
 
            // Now look for the third number
            for (int k = j + 1; k < arr_size; k++) {
                if (A[i] + A[j] + A[k] == sum) {
                    printf("Triplet is %d, %d, %d",
                           A[i], A[j], A[k]);
                    return true;
                }
            }
        }
    }
 
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver program to test above function */
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




// Java program to find a triplet
class FindTriplet {
 
    // returns true if there is triplet with sum equal
    // to 'sum' present in A[]. Also, prints the triplet
    boolean find3Numbers(int A[], int arr_size, int sum)
    {
        int l, r;
 
        // Fix the first element as A[i]
        for (int i = 0; i < arr_size - 2; i++) {
 
            // Fix the second element as A[j]
            for (int j = i + 1; j < arr_size - 1; j++) {
 
                // Now look for the third number
                for (int k = j + 1; k < arr_size; k++) {
                    if (A[i] + A[j] + A[k] == sum) {
                        System.out.print("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]);
                        return true;
                    }
                }
            }
        }
 
        // If we reach here, then no triplet was found
        return false;
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        FindTriplet triplet = new FindTriplet();
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int sum = 22;
        int arr_size = A.length;
 
        triplet.find3Numbers(A, arr_size, sum);
    }
}

Python3




# Python3 program to find a triplet
# that sum to a given value
 
# returns true if there is triplet with
# sum equal to 'sum' present in A[].
# Also, prints the triplet
def find3Numbers(A, arr_size, sum):
 
    # Fix the first element as A[i]
    for i in range( 0, arr_size-2):
 
        # Fix the second element as A[j]
        for j in range(i + 1, arr_size-1):
             
            # Now look for the third number
            for k in range(j + 1, arr_size):
                if A[i] + A[j] + A[k] == sum:
                    print("Triplet is", A[i],
                          ", ", A[j], ", ", A[k])
                    return True
     
    # If we reach here, then no
    # triplet was found
    return False
 
# Driver program to test above function
A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)
 
# This code is contributed by Smitha Dinesh Semwal

C#




// C# program to find a triplet
// that sum to a given value
using System;
 
class GFG {
    // returns true if there is
    // triplet with sum equal
    // to 'sum' present in A[].
    // Also, prints the triplet
    static bool find3Numbers(int[] A,
                             int arr_size,
                             int sum)
    {
        // Fix the first
        // element as A[i]
        for (int i = 0;
             i < arr_size - 2; i++) {
 
            // Fix the second
            // element as A[j]
            for (int j = i + 1;
                 j < arr_size - 1; j++) {
 
                // Now look for
                // the third number
                for (int k = j + 1;
                     k < arr_size; k++) {
                    if (A[i] + A[j] + A[k] == sum) {
                        Console.WriteLine("Triplet is " + A[i] + ", " + A[j] + ", " + A[k]);
                        return true;
                    }
                }
            }
        }
 
        // If we reach here,
        // then no triplet was found
        return false;
    }
 
    // Driver Code
    static public void Main()
    {
        int[] A = { 1, 4, 45, 6, 10, 8 };
        int sum = 22;
        int arr_size = A.Length;
 
        find3Numbers(A, arr_size, sum);
    }
}
 
// This code is contributed by m_kit

PHP




<?php
// PHP program to find a triplet
// that sum to a given value
 
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[].
// Also, prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
    $l; $r;
 
    // Fix the first
    // element as A[i]
    for ($i = 0;
         $i < $arr_size - 2; $i++)
    {
    // Fix the second
    // element as A[j]
    for ($j = $i + 1;
         $j < $arr_size - 1; $j++)
    {
        // Now look for the
        // third number
        for ($k = $j + 1;
             $k < $arr_size; $k++)
        {
            if ($A[$i] + $A[$j] +
                $A[$k] == $sum)
            {
                echo "Triplet is", " ", $A[$i],
                                  ", ", $A[$j],
                                  ", ", $A[$k];
                return true;
            }
        }
    }
    }
 
    // If we reach here, then
    // no triplet was found
    return false;
}
// Driver Code
$A = array(1, 4, 45,
           6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
 
find3Numbers($A, $arr_size, $sum);
 
// This code is contributed by ajit
?>

Javascript




<script>
 
// Javascript program to find a triplet
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
function find3Numbers(A, arr_size, sum)
{
    let l, r;
 
    // Fix the first element as A[i]
    for (let i = 0; i < arr_size - 2; i++)
    {
 
        // Fix the second element as A[j]
        for (let j = i + 1; j < arr_size - 1; j++)
        {
 
            // Now look for the third number
            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;
                }
            }
        }
    }
 
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver code */
  
    let A = [ 1, 4, 45, 6, 10, 8 ];
    let sum = 22;
    let arr_size = A.length;
    find3Numbers(A, arr_size, sum);
     
// This code is contributed by Mayank Tyagi
 
</script>

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: using recursion

Implementation steps:

  • Define a function that will take the input array, the target sum, and any other necessary parameters as input and return the triplet that adds up to the target sum or a message indicating that no such triplet exists.
  • Implement the function to check all possible subsets of the array to find a triplet with a sum of the target value. This can be done using recursion.
  • Call the function with the input array and target sum as arguments and print the result.

Implementations:

C++




#include <bits/stdc++.h>
using namespace std;
 
// The check function recursively checks all possible subsets of the array
//  to see if any of them sum to the target value
bool check(int n,int arr[],int target, vector<int> triplet)
{
      // If the target value has been reached and the length of the triplet is 3,
    // then a triplet with a sum of target has been found and is printed
    if(target==0 and triplet.size()==3){
        cout<<triplet[0]<<" "<<triplet[1]<<" "<<triplet[2]<<endl;
        return true;
    }
   
    // If there are no more elements in the array or the target value has gone negative,
    // then a triplet with a sum of target cannot be found
    if(n == 0 or target < 0 or triplet.size() == 3)
          return false;
   
      triplet.push_back(arr[n-1]);
   
    // Recursively check if target can be reached by including the current element in the triplet
    // or by excluding the current element and checking the remaining elements
    bool a = check(n-1, arr, target-arr[n-1], triplet);
   
      triplet.pop_back();
   
    bool b = check(n-1, arr, target, triplet);
   
      return a|b;
}
int main() {
       
      //array length
    int n = 6;
   
      //array
    int arr[] = {1, 4, 45, 6, 10, 8};
   
      //target value
    int target = 22;
   
      //taking expty array for triplet
      vector<int> triplet;
   
      //calling function
    if(!check(n,arr,target,triplet)){
      cout<<"does not exist"<<endl;
    }
   
    return 0;
}
//code contributed by shubhamrajput6156

Java




import java.util.ArrayList;
 
public class Main
{
   
    // The check function recursively checks all possible subsets of the array
    // to see if any of them sum to the target value
    public static boolean check(int n, int[] arr, int target, ArrayList<Integer> triplet) {
         
      // If the target value has been reached and the length of the triplet is 3,
        // then a triplet with a sum of target has been found and is printed
        if (target == 0 && triplet.size() == 3) {
            System.out.println(triplet.get(0) + " " + triplet.get(1) + " " + triplet.get(2));
            return true;
        }
 
        // If there are no more elements in the array or the target value has gone negative,
        // then a triplet with a sum of target cannot be found
        if (n == 0 || target < 0 || triplet.size() == 3)
            return false;
 
        triplet.add(arr[n - 1]);
 
        // Recursively check if target can be reached by including the current element in the triplet
        // or by excluding the current element and checking the remaining elements
        boolean a = check(n - 1, arr, target - arr[n - 1], triplet);
 
        triplet.remove(triplet.size() - 1);
 
        boolean b = check(n - 1, arr, target, triplet);
 
        return a | b;
    }
 
    public static void main(String[] args) {
        // array length
        int n = 6;
 
        // array
        int[] arr = {1, 4, 45, 6, 10, 8};
 
        // target value
        int target = 22;
 
        // taking empty array for triplet
        ArrayList<Integer> triplet = new ArrayList<>();
 
        // calling function
        if (!check(n, arr, target, triplet)) {
            System.out.println("does not exist");
        }
    }
}

Python




# python program for above approach
 
array = [1, 4, 45, 6, 10, 8]
target = 22
n = len(array)
 
# The check function recursively checks all possible subsets of the array
# to see if any of them sum to the target value
def check(array, n, target, triplet):
    # If the target value has been reached and the length of the triplet is 3,
    # then a triplet with a sum of target has been found and is printed
    if target == 0 and len(triplet) == 3:
        print(triplet)
        return True
     
    # If there are no more elements in the array or the target value has gone negative,
    # then a triplet with a sum of target cannot be found
    if n == 0 or target < 0 or len(triplet) == 3:
        return False
     
    # Recursively check if target can be reached by including the current element in the triplet
    # or by excluding the current element and checking the remaining elements
    return (check(array, n-1, target-array[n-1], triplet+[array[n-1]])
            or check(array, n-1, target, triplet))
 
# Call the check function with an empty triplet to start checking all possible subsets of the array
if not check(array, n, target, []):
    print('does not exist')
     
# this code is contributed by bhardwajji

C#




using System;
using System.Collections.Generic;
 
class Program {
  static bool Check(int n, int[] arr, int target,
                    List<int> triplet)
  {
 
    // If the target value has been reached and the
    // length of the triplet is 3, then a triplet with a
    // sum of target has been found and is printed
    if (target == 0 && triplet.Count == 3) {
      Console.WriteLine(triplet[0] + " " + triplet[1]
                        + " " + triplet[2]);
      return true;
    }
 
    // If there are no more elements in the array or the
    // target value has gone negative, then a triplet
    // with a sum of target cannot be found
    if (n == 0 || target < 0 || triplet.Count == 3)
      return false;
 
    triplet.Add(arr[n - 1]);
 
    // Recursively check if target can be reached by
    // including the current element in the triplet or
    // by excluding the current element and checking the
    // remaining elements
    bool a = Check(n - 1, arr, target - arr[n - 1],
                   triplet);
 
    triplet.RemoveAt(triplet.Count - 1);
 
    bool b = Check(n - 1, arr, target, triplet);
 
    return a || b;
  }
 
  static void Main(string[] args)
  {
    // array length
    int n = 6;
 
    // array
    int[] arr = { 1, 4, 45, 6, 10, 8 };
 
    // target value
    int target = 22;
 
    // taking empty list for triplet
    List<int> triplet = new List<int>();
 
    // calling function
    if (!Check(n, arr, target, triplet)) {
      Console.WriteLine("does not exist");
    }
 
    Console.ReadLine();
  }
}
 
// This code is contributed by user_dtewbxkn77n

Javascript




let array = [1, 4, 45, 6, 10, 8];
let target = 22;
let n = array.length;
 
// The check function recursively checks all possible subsets of the array
// to see if any of them sum to the target value
function check(array, n, target, triplet) {
    // If the target value has been reached and the length of the triplet is 3,
    // then a triplet with a sum of target has been found and is printed
    if (target == 0 && triplet.length == 3) {
        console.log(triplet);
        return true;
    }
     
    // If there are no more elements in the array or the target value has gone negative,
    // then a triplet with a sum of target cannot be found
    if (n == 0 || target < 0 || triplet.length == 3) {
        return false;
    }
     
    // Recursively check if target can be reached by including the current element in the triplet
    // or by excluding the current element and checking the remaining elements
    return (check(array, n-1, target-array[n-1], [...triplet,array[n-1]])
            || check(array,n-1,target,[...triplet]));
}
 
// Call the check function with an empty triplet to start checking all possible subsets of the array
if (!check(array,n,target,[])) {
    console.log('does not exist');
}

Output

[8, 10, 4]

Time complexity: O(2^N), because this solution made recursive tree.
Auxiliary Space: O(1)

Method 3: 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++




// C++ program to find a triplet
#include <bits/stdc++.h>
using namespace std;
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    int l, r;
    /* Sort the elements */
    sort(A, A + arr_size);
    /* Now fix the first element one by one and find the
       other two elements */
    for (int i = 0; i < arr_size - 2; i++) {
 
        // To find the other two elements, start two index
        // variables from two corners of the array and move
        // them toward each other
        l = i + 1; // index of the first element in the
        // remaining elements
        r = arr_size - 1; // index of the last element
        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 // A[i] + A[l] + A[r] > sum
                r--;
        }
    }
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver program to test above function */
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;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C




// C program to find a triplet
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
 
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    int l, r;
   
    /* Sort the elements */
    qsort(A, arr_size, sizeof(int), cmpfunc);
   
    /* Now fix the first element one by one and find the
       other two elements */
    for (int i = 0; i < arr_size - 2; i++)
    {
       
        // To find the other two elements, start two index
        // variables from two corners of the array and move
        // them toward each other
        l = i + 1; // index of the first element in the
        // remaining elements
        r = arr_size - 1; // index of the last element
        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 // A[i] + A[l] + A[r] > sum
                r--;
        }
    }
   
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver program to test above function */
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;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java




// Java program to find a triplet
class FindTriplet {
 
    // returns true if there is triplet with sum equal
    // to 'sum' present in A[]. Also, prints the triplet
    boolean find3Numbers(int A[], int arr_size, int sum)
    {
        int l, r;
 
        /* Sort the elements */
        quickSort(A, 0, arr_size - 1);
 
        /* Now fix the first element one by one and find the
           other two elements */
        for (int i = 0; i < arr_size - 2; i++) {
 
            // To find the other two elements, start two
            // index variables from two corners of the array
            // and move them toward each other
            l = i + 1; // index of the first element in the
                       // remaining elements
            r = arr_size - 1; // index of the last element
            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 // A[i] + A[l] + A[r] > sum
                    r--;
            }
        }
 
        // If we reach here, then no triplet was found
        return false;
    }
 
    int partition(int A[], int si, int ei)
    {
        int x = A[ei];
        int i = (si - 1);
        int j;
 
        for (j = si; j <= ei - 1; j++) {
            if (A[j] <= x) {
                i++;
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            }
        }
        int temp = A[i + 1];
        A[i + 1] = A[ei];
        A[ei] = temp;
        return (i + 1);
    }
 
    /* Implementation of Quick Sort
    A[] --> Array to be sorted
    si  --> Starting index
    ei  --> Ending index
     */
    void quickSort(int A[], int si, int ei)
    {
        int pi;
 
        /* Partitioning index */
        if (si < ei) {
            pi = partition(A, si, ei);
            quickSort(A, si, pi - 1);
            quickSort(A, pi + 1, ei);
        }
    }
 
    // Driver program to test above functions
    public static void main(String[] args)
    {
        FindTriplet triplet = new FindTriplet();
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int sum = 22;
        int arr_size = A.length;
 
        triplet.find3Numbers(A, arr_size, sum);
    }
}

Python3




# Python3 program to find a triplet
 
# returns true if there is triplet
# with sum equal to 'sum' present
# in A[]. Also, prints the triplet
def find3Numbers(A, arr_size, sum):
 
    # Sort the elements
    A.sort()
 
    # Now fix the first element
    # one by one and find the
    # other two elements
    for i in range(0, arr_size-2):
     
 
        # To find the other two elements,
        # start two index variables from
        # two corners of the array and
        # move them toward each other
         
        # index of the first element
        # in the remaining elements
        l = i + 1
         
        # index of the last element
        r = arr_size-1
        while (l < r):
         
            if( A[i] + A[l] + A[r] == sum):
                print("Triplet is", A[i],
                     ', ', A[l], ', ', A[r]);
                return True
             
            elif (A[i] + A[l] + A[r] < sum):
                l += 1
            else: # A[i] + A[l] + A[r] > sum
                r -= 1
 
    # If we reach here, then
    # no triplet was found
    return False
 
# Driver program to test above function
A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
 
find3Numbers(A, arr_size, sum)
 
# This is contributed by Smitha Dinesh Semwal

C#




// C# program to find a triplet
using System;
 
class GFG {
 
    // returns true if there is triplet
    // with sum equal to 'sum' present
    // in A[]. Also, prints the triplet
    bool find3Numbers(int[] A, int arr_size,
                      int sum)
    {
        int l, r;
 
        /* Sort the elements */
        quickSort(A, 0, arr_size - 1);
 
        /* Now fix the first element
    one by one and find the
    other two elements */
        for (int i = 0; i < arr_size - 2; i++) {
 
            // To find the other two elements,
            // start two index variables from
            // two corners of the array and
            // move them toward each other
            l = i + 1; // index of the first element
            // in the remaining elements
            r = arr_size - 1; // index of the last element
            while (l < r) {
                if (A[i] + A[l] + A[r] == sum) {
                    Console.Write("Triplet is " + A[i] + ", " + A[l] + ", " + A[r]);
                    return true;
                }
                else if (A[i] + A[l] + A[r] < sum)
                    l++;
 
                else // A[i] + A[l] + A[r] > sum
                    r--;
            }
        }
 
        // If we reach here, then
        // no triplet was found
        return false;
    }
 
    int partition(int[] A, int si, int ei)
    {
        int x = A[ei];
        int i = (si - 1);
        int j;
 
        for (j = si; j <= ei - 1; j++) {
            if (A[j] <= x) {
                i++;
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            }
        }
        int temp1 = A[i + 1];
        A[i + 1] = A[ei];
        A[ei] = temp1;
        return (i + 1);
    }
 
    /* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
    void quickSort(int[] A, int si, int ei)
    {
        int pi;
 
        /* Partitioning index */
        if (si < ei) {
            pi = partition(A, si, ei);
            quickSort(A, si, pi - 1);
            quickSort(A, pi + 1, ei);
        }
    }
 
    // Driver Code
    static void Main()
    {
        GFG triplet = new GFG();
        int[] A = new int[] { 1, 4, 45, 6, 10, 8 };
        int sum = 22;
        int arr_size = A.Length;
 
        triplet.find3Numbers(A, arr_size, sum);
    }
}
 
// This code is contributed by mits

PHP




<?php
// PHP program to find a triplet
 
// returns true if there is
// triplet with sum equal to
// 'sum' present in A[]. Also,
// prints the triplet
function find3Numbers($A, $arr_size, $sum)
{
    $l; $r;
 
    /* Sort the elements */
    sort($A);
 
    /* Now fix the first element
    one by one and find the
    other two elements */
    for ($i = 0; $i < $arr_size - 2; $i++)
    {
 
        // To find the other two elements,
        // start two index variables from
        // two corners of the array and
        // move them toward each other
        $l = $i + 1; // index of the first element
                     // in the remaining elements
 
        // index of the last element
        $r = $arr_size - 1;
        while ($l < $r)
        {
            if ($A[$i] + $A[$l] +
                $A[$r] == $sum)
            {
                echo "Triplet is ", $A[$i], " ",
                                    $A[$l], " ",
                                    $A[$r], "\n";
                return true;
            }
            else if ($A[$i] + $A[$l] +
                     $A[$r] < $sum)
                $l++;
            else // A[i] + A[l] + A[r] > sum
                $r--;
        }
    }
 
    // If we reach here, then
    // no triplet was found
    return false;
}
 
// Driver Code
$A = array (1, 4, 45, 6, 10, 8);
$sum = 22;
$arr_size = sizeof($A);
 
find3Numbers($A, $arr_size, $sum);
 
// This code is contributed by ajit
?>

Javascript




<script>
 
// Javascript program to find a triplet
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
function find3Numbers(A, arr_size, sum)
{
    let l, r;
 
    /* Sort the elements */
    A.sort((a,b) => a-b);
 
    /* Now fix the first element one
    by one and find the
    other two elements */
    for (let i = 0; i < arr_size - 2; i++) {
 
        // To find the other two
        // elements, start two index
        // variables from two corners of
        // the array and move
        // them toward each other
         
        // index of the first element in the
        l = i + 1;
         
        // remaining elements
         
       // index of the last element
        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 // A[i] + A[l] + A[r] > sum
                r--;
        }
    }
 
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver program to test above function */
 
    let A = [ 1, 4, 45, 6, 10, 8 ];
    let sum = 22;
    let arr_size = A.length;
 
    find3Numbers(A, arr_size, sum);
 
 
// This code is contributed by Mayank Tyagi
 
</script>

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 4: 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 n-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++




// C++ program to find a triplet using Hashing
#include <bits/stdc++.h>
using namespace std;
 
// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    // Fix the first element as A[i]
    for (int i = 0; i < arr_size - 2; i++)
    {
 
        // Find pair in subarray A[i+1..n-1]
        // with sum equal to sum - A[i]
        unordered_set<int> 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]);
        }
    }
 
    // If we reach here, then no triplet was found
    return false;
}
 
/* Driver program to test above function */
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




// Java program to find a triplet using Hashing
import java.util.*;
 
class GFG {
 
    // returns true if there is triplet
    // with sum equal to 'sum' present
    // in A[]. Also, prints the triplet
    static boolean find3Numbers(int A[],
                                int arr_size, int sum)
    {
        // Fix the first element as A[i]
        for (int i = 0; i < arr_size - 2; i++) {
 
            // Find pair in subarray A[i+1..n-1]
            // with sum equal to sum - A[i]
            HashSet<Integer> s = new HashSet<Integer>();
            int curr_sum = sum - A[i];
            for (int j = i + 1; j < arr_size; j++)
            {
                if (s.contains(curr_sum - A[j]))
                {
                    System.out.print("Triplet is " + A[i] + ", " + A[j] + ", " + (curr_sum - A[j]));
                    return true;
                }
                s.add(A[j]);
            }
        }
 
        // If we reach here, then no triplet was found
        return false;
    }
 
    /* Driver code */
    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);
    }
}
 
// This code has been contributed by 29AjayKumar
// This code is improved by Susobhan Akhuli

Python3




# Python3 program to find a triplet using Hashing
# returns true if there is triplet with sum equal
# to 'sum' present in A[]. Also, prints the triplet
def find3Numbers(A, arr_size, sum):
    for i in range(0, arr_size-1):
        # Find pair in subarray A[i + 1..n-1]
        # with sum equal to sum - A[i]
        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
 
# Driver program to test above function
A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)
 
# This is contributed by Yatin gupta

C#




// C# program to find a triplet using Hashing
using System;
using System.Collections.Generic;
public class GFG {
 
    // returns true if there is triplet
    // with sum equal to 'sum' present
    // in A[]. Also, prints the triplet
    static bool find3Numbers(int[] A,
                             int arr_size, int sum)
    {
        // Fix the first element as A[i]
        for (int i = 0; i < arr_size - 2; i++) {
 
            // Find pair in subarray A[i+1..n-1]
            // with sum equal to sum - A[i]
            HashSet<int> s = new HashSet<int>();
            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]);
            }
        }
 
        // If we reach here, then no triplet was found
        return false;
    }
 
    /* Driver code */
    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);
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript




<script>
 
// JavaScript program to find a triplet using Hashing
 
    // returns true if there is triplet
    // with sum equal to 'sum' present
    // in A[]. Also, prints the triplet
    function find3Numbers(A,arr_size,sum)
    {
        // Fix the first element as A[i]
        for (let i = 0; i < arr_size - 2; i++) {
   
            // Find pair in subarray A[i+1..n-1]
            // with sum equal to sum - A[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])+"<br>"
                    );
                     
                    return true;
                }
                s.add(A[j]);
            }
        }
   
        // If we reach here, then no triplet was found
        return false;
    }
     
    /* Driver code */
    let A=[1, 4, 45, 6, 10, 8];
     
    let sum = 22;
    let arr_size = A.length;
    find3Numbers(A, arr_size, sum);
 
// This code is contributed by rag2127
 
</script>

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.


My Personal Notes arrow_drop_up
Last Updated : 18 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials