# 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

Input : arr[] = {1, -2, 1, 0, 5}
sum = 0
Output : 1 -2  1
```

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Method 1 (Simple : O(n3))
The naive approach is that run three loops and check one by one that sum of three elements is given sum or not If sum of three elements is given sum, then print elements other wise print not found.

## C++

 `// A simple C++ program to find three elements ` `// whose sum is equal to given sum ` `#include ` `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); ` `    ``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

 ` `

Output :

```0 -3 1
-1 2 -3
```

Time Complexity : O(n3)
Auxiliary Space : O(1)

Method 2 (Hashing : O(n2))
We iterate through every element. For every element arr[i], we find a pair with sum “-arr[i]”. This problem reduces to pairs sum and can be solved in O(n) time using hashing.

```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 ` `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); ` `    ``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 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` `=` `-``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 - 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 `

Output:

```-3 0 1
2 -1 -3
```

Time Complexity : O(n2)
Auxiliary Space : O(n)

Method 3 (Sorting : O(n2))
The above method requires extra space. We can solve in O(1) extra space. The idea is based on method 2 of this post.

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

## C++

 `// C++ program to find triplets in a given ` `// array whose sum is given sum. ` `#include ` `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); ` `    ``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

 ` `

Output:

```-3 -1 2
-3 0 1
```

Time Complexity : O(n2)
Auxiliary Space : O(1)

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.