# Find all triplets with zero sum

Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.

Examples :

```Input : arr[] = {0, -1, 2, -3, 1}
Output : (0 -1 1), (2 -3 1)

Explanation : The triplets with zero sum are
0 + -1 + 1 = 0 and 2 + -3 + 1 = 0

Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2  1
Explanation : The triplets with zero sum is
1 + -2 + 1 = 0

```

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

Method 1: This is a simple method that takes O(n3) time to arrive at the result.

• Approach: The naive approach run three loops and check one by one that sum of three elements is zero or not. If the sum of three elements is zero then print elements otherwise print not found.
• Algorithm:
1. Run three nested loops with loop counter i, j, k
2. The three loops will run from 0 to n-3 and second loop from i+1 to n-2 and the third loop from j+1 to n-1. The loop counter represents the three elements of the triplet.
3. check if the sum of elements at i’th, j’th, k’th is equal to zero or not. If yes print the sum else continue.
• Implementation:

## C++

 `// A simple C++ program to find three elements ` `// whose sum is equal to zero ` `#include ` `using` `namespace` `std; ` ` `  `// Prints all triplets in arr[] with 0 sum ` `void` `findTriplets(``int` `arr[], ``int` `n) ` `{ ` `    ``bool` `found = ``true``; ` `    ``for` `(``int` `i=0; i

## Java

 `// A simple Java program to find three elements ` `// whose sum is equal to zero ` `class` `num{ ` `// Prints all triplets in arr[] with 0 sum ` `static` `void` `findTriplets(``int``[] arr, ``int` `n) ` `{ ` `    ``boolean` `found = ``true``; ` `    ``for` `(``int` `i=``0``; i

## Python3

 `# A simple Python 3 program  ` `# to find three elements whose  ` `# sum is equal to zero ` ` `  `# Prints all triplets in  ` `# arr[] with 0 sum ` `def` `findTriplets(arr, n): ` ` `  `    ``found ``=` `True` `    ``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] ``=``=` `0``): ` `                    ``print``(arr[i], arr[j], arr[k]) ` `                    ``found ``=` `True` `     `  `             `  `    ``# If no triplet with 0 sum  ` `    ``# found in array ` `    ``if` `(found ``=``=` `False``): ` `        ``print``(``" not exist "``) ` ` `  `# Driver code ` `arr ``=` `[``0``, ``-``1``, ``2``, ``-``3``, ``1``] ` `n ``=` `len``(arr) ` `findTriplets(arr, n) ` ` `  `# This code is contributed by Smitha Dinesh Semwal     `

## C#

 `// A simple C# program to find three elements  ` `// whose sum is equal to zero ` `using` `System; ` ` `  `class` `GFG { ` `     `  `    ``// Prints all triplets in arr[] with 0 sum ` `    ``static` `void` `findTriplets(``int` `[]arr, ``int` `n) ` `    ``{ ` `        ``bool` `found = ``true``; ` `        ``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] ` `                                           ``== 0) ` `                    ``{ ` `                        ``Console.Write(arr[i]); ` `                        ``Console.Write(``" "``); ` `                        ``Console.Write(arr[j]); ` `                        ``Console.Write(``" "``); ` `                        ``Console.Write(arr[k]); ` `                        ``Console.Write(``"\n"``); ` `                        ``found = ``true``; ` `                    ``} ` `                ``} ` `            ``} ` `        ``} ` `     `  `        ``// If no triplet with 0 sum found in  ` `        ``// array ` `        ``if` `(found == ``false``) ` `            ``Console.Write(``" not exist "``); ` `    ``} ` `     `  `    ``// Driver code ` `    ``public` `static` `void` `Main() ` `    ``{ ` `        ``int` `[]arr = {0, -1, 2, -3, 1}; ` `        ``int` `n = arr.Length; ` `        ``findTriplets(arr, n); ` `    ``} ` `} ` ` `  `// This code is contributed by nitin mittal. `

## PHP

 ` `

Output:

```0 -1 1
2 -3 1```
• Complexity Analysis:
• Time Complexity : O(n3).
As three nested loops are required, so the time complexity is O(n3).
• Auxiliary Space : O(1).
Since no extra space is required, so the time complexity is constant.

Method 2: The second method uses the process of Hashing to arrive at the result and is solved at a lesser time of O(n2).

• Approach: This involves traversing through the array. For every element arr[i], find a pair with sum “-arr[i]”. This problem reduces to pairs sum and can be solved in O(n) time using hashing.
• Algorithm:
1. Create a hashap to store a key value pair.
2. Run a nested loop with two loops, outer loop from 0 to n-2 and the inner loop from i+1 to n-1
3. Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not
4. If the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
• Implementation:

## C++

 `// C++ program to find triplets in a given ` `// array whose sum is zero ` `#include ` `using` `namespace` `std; ` ` `  `// function to print triplets with 0 sum ` `void` `findTriplets(``int` `arr[], ``int` `n) ` `{ ` `    ``bool` `found = ``false``; ` ` `  `    ``for` `(``int` `i=0; i s; ` `        ``for` `(``int` `j=i+1; j

## Java

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

## Python3

 `# Python3 program to find triplets  ` `# in a given array whose sum is zero  ` ` `  `# function to print triplets with 0 sum  ` `def` `findTriplets(arr, n): ` `    ``found ``=` `False` `    ``for` `i ``in` `range``(n ``-` `1``): ` ` `  `        ``# Find all pairs with sum  ` `        ``# equals to "-arr[i]"  ` `        ``s ``=` `set``() ` `        ``for` `j ``in` `range``(i ``+` `1``, n): ` `            ``x ``=` `-``(arr[i] ``+` `arr[j]) ` `            ``if` `x ``in` `s: ` `                ``print``(x, arr[i], arr[j]) ` `                ``found ``=` `True` `            ``else``: ` `                ``s.add(arr[j]) ` `    ``if` `found ``=``=` `False``: ` `        ``print``(``"No Triplet Found"``) ` ` `  `# Driver Code ` `arr ``=` `[``0``, ``-``1``, ``2``, ``-``3``, ``1``] ` `n ``=` `len``(arr) ` `findTriplets(arr, n) ` ` `  `# This code is contributed by Shrikant13 `

## C#

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

Output:

```-1 0 1
-3 2 1
```
• Complexity Analysis:
• Time Complexity: O(n2).
Since two nested loops is required, so the time complexity is O(n2).
• Auxiliary Space: O(n).
Since a hashmap is required, so the time complexity is linear.

Method 3: This method uses Sorting to arrive at the correct result and is solved in O(n2) time.

• Approach: The above method requires extra space. The idea is based on method 2 of this post. For every element check that there is a pair whose sum is equal to the negative value of that element.
• Algorithm:
1. Sort the array in ascending order.
2. Traverse the array from start to end.
3. For every index i, create two variables l = i + 1 and r = n – 1
4. Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop
5. If the sum is less than zero then increment value of l, by increasing value of l the sum will increase as the array is sorted, so array[l+1] > array [l]
6. If the sum is greater than zero then decrement value of r, by increasing value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].
• Implementation:

## C++

 `// C++ program to find triplets in a given ` `// array whose sum is zero ` `#include ` `using` `namespace` `std; ` ` `  `// function to print triplets with 0 sum ` `void` `findTriplets(``int` `arr[], ``int` `n) ` `{ ` `    ``bool` `found = ``false``; ` ` `  `    ``// sort array elements ` `    ``sort(arr, arr+n); ` ` `  `    ``for` `(``int` `i=0; i

## Java

 `// Java  program to find triplets in a given ` `// array whose sum is zero ` `import` `java.util.Arrays;  ` `import` `java.io.*; ` ` `  `class` `GFG { ` `    ``// function to print triplets with 0 sum ` `static` `void` `findTriplets(``int` `arr[], ``int` `n) ` `{ ` `    ``boolean` `found = ``false``; ` ` `  `    ``// sort array elements ` `    ``Arrays.sort(arr); ` ` `  `    ``for` `(``int` `i=``0``; i

## Python3

 `# python program to find triplets in a given ` `# array whose sum is zero ` ` `  `# function to print triplets with 0 sum ` `def` `findTriplets(arr, n): ` ` `  `    ``found ``=` `False` ` `  `    ``# 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] ``=``=` `0``): ` `                ``# print elements if it's sum is zero ` `                ``print``(x, arr[l], arr[r]) ` `                ``l``+``=``1` `                ``r``-``=``1` `                ``found ``=` `True` `             `  ` `  `            ``# If sum of three elements is less ` `            ``# than zero then increment in left ` `            ``elif` `(x ``+` `arr[l] ``+` `arr[r] < ``0``): ` `                ``l``+``=``1` ` `  `            ``# if sum is greater than zero than ` `            ``# decrement in right side ` `            ``else``: ` `                ``r``-``=``1` `         `  `    ``if` `(found ``=``=` `False``): ` `        ``print``(``" No Triplet Found"``) ` ` `  ` `  `# Driven source ` `arr ``=` `[``0``, ``-``1``, ``2``, ``-``3``, ``1``] ` `n ``=` `len``(arr) ` `findTriplets(arr, n) ` ` `  `# This code is contributed by Smitha Dinesh Semwal `

## C#

 `// C#  program to find triplets in a given ` `// array whose sum is zero ` `using` `System; ` ` `  `public` `class` `GFG{ ` `        ``// function to print triplets with 0 sum ` `static` `void` `findTriplets(``int` `[]arr, ``int` `n) ` `{ ` `    ``bool` `found = ``false``; ` ` `  `    ``// sort array elements ` `    ``Array.Sort(arr); ` ` `  `    ``for` `(``int` `i=0; i

## PHP

 ` `

Output :

```-3 1 2
-1 0 1
```
• Complexity Analysis:

• Time Complexity : O(n2).
only two nested loops is required, so the time complexity is O(n2).
• Auxiliary Space : O(1), no extra space is required, so the time complexity is constant.

This article is contributed by DANISH_RAZA. 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.

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.

My Personal Notes arrow_drop_up

Article Tags :

48

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.