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:
- Take three pointers i, j, k.
- Intialize i with zero and start a nested loop for i.
- Intialize j with (i+1) and start a nested loop for j.
- Initialize k with (j+1) and start a loop for k.
- If Target == arr[i] + arr[j] + arr[k] break the loop and print values of arr[i], arr[j], arr[k].
- Else keep incrementing k till it is equal to last index.
- Goto step 2 and increment j and for every value of j run the inner loop of k.
- 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++
// 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 |
Python 3
# 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 ?> |
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:
- Start the outer loop from i=0 till the (n-2)th index.
- For every iteration make an unordered set and enter the inner loop.
- 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.
- Check if the element x = Target -(arr[i] + arr[j]) is present then the triplet is found and hence printed.
- Else push the value in the set as for later reference.
- 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++
// 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; } |
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 - 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 |
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 - 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 = -2n = 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 - 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 |
-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:
- 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.
- Searching for the other two elements can be done efficiently using Two-pointer technique as the array is sorted.
- 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.
- Now enter into a while loop which will run till the value of l<r.
- 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.
- 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.
- If arr[i]+arr[l]+arr[r]==Target sum print the values.
- 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++
// 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; } |
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 ?> |
-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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Print triplets with sum less than k
- Print all triplets in sorted array that form AP
- Count of Triplets
- All unique triplets that sum up to a given value
- Find all triplets with zero sum
- Count the triplets such that A[i] < B[j] < C[k]
- Count triplets in an array such that i<j<k and a[j] - a[i] = a[k] - a[j] = D
- Count of triplets in an Array such that A[i] * A[j] = A[k] and i < j < k
- Number of unique triplets whose XOR is zero
- Count triplets such that sum of any two number is equal to third | Set 2
- Triplets in array with absolute difference less than k
- Count Triplets such that one of the numbers can be written as sum of the other two
- Count of triplets from the given Array such that sum of any two elements is the third element
- Count number of triplets in an array having sum in the range [a, b]
- Count of triplets in an array that satisfy the given conditions
- Total number of triplets (A, B, C) in which the points B and C are Equidistant to A
- Count of ordered triplets (R, G, B) in a given original string
- Maximum number of unique Triplets such that each element is selected only once
- Count of ways to split N into Triplets forming a Triangle
- Count ways to form minimum product triplets
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.

