Given an array of distinct elements. The task is to find triplets in array whose sum is zero.
Examples :
Input : arr[] = {0, -1, 2, -3, 1}
Output : 0 -1 1
2 -3 1
Input : arr[] = {1, -2, 1, 0, 5}
Output : 1 -2 1
Method 1 (Simple : O(n3))
The naive approach is that run three loops and check one by one that sum of three elements is zero or not if sum of three elements is zero then print elements other wise print not found.
C++
// A simple C++ program to find three elements // whose sum is equal to zero #include<bits/stdc++.h> 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<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) { cout << arr[i] << " " << arr[j] << " " << arr[k] <<endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << " not exist "<<endl; } // Driver code int main() { int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0; } |
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<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) { System.out.print(arr[i]); System.out.print(" "); System.out.print(arr[j]); System.out.print(" "); System.out.print(arr[k]); System.out.print("\n"); found = true; } } } } // If no triplet with 0 sum found in array if (found == false) System.out.println(" not exist "); } // Driver code public static void main(String[] args) { int arr[] = {0, -1, 2, -3, 1}; int n =arr.length; findTriplets(arr, n); } } //This code is contributed by //Smitha Dinesh Semwal |
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
<?php // A simple PHP program to // find three elements whose // sum is equal to zero // Prints all triplets // in arr[] with 0 sum function findTriplets($arr, $n) { $found = true; 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] == 0) { echo $arr[$i] , " ", $arr[$j] , " ", $arr[$k] ,"\n"; $found = true; } } } } // If no triplet with 0 // sum found in array if ($found == false) echo " not exist ", "\n"; } // Driver Code $arr = array (0, -1, 2, -3, 1); $n = sizeof($arr); findTriplets($arr, $n); // This code is contributed by m_kit ?> |
0 -1 1 2 -3 1
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 zero #include<bits/stdc++.h> using namespace std; // function to print triplets with 0 sum 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]" unordered_set<int> s; for (int j=i+1; j<n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf("%d %d %d\n", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << " No Triplet Found" << endl; } // Driver code int main() { int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0; } |
-1 0 1 -3 2 1
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
zero or not if sum is zero then print the
triplet and do l++ and r--.
5. If sum is less than zero then l++
6. If sum is greater than zero 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 zero #include<bits/stdc++.h> 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<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] == 0) { // print elements if it's sum is zero printf("%d %d %d\n", x, arr[l], arr[r]); l++; r--; found = true; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero than // decrement in right side else r--; } } if (found == false) cout << " No Triplet Found" << endl; } // Driven source int main() { int arr[] = {0, -1, 2, -3, 1}; int n = sizeof(arr)/sizeof(arr[0]); findTriplets(arr, n); return 0; } |
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 |
PHP
<?php // PHP program to find // triplets in a given // array whose sum is zero // function to print // triplets with 0 sum function findTriplets($arr, $n) { $found = false; // 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] == 0) { // print elements if // it's sum is zero echo $x," ", $arr[$l], " ", $arr[$r], "\n"; $l++; $r--; $found = true; } // If sum of three elements // is less than zero then // increment in left else if ($x + $arr[$l] + $arr[$r] < 0) $l++; // if sum is greater than // zero than decrement // in right side else $r--; } } if ($found == false) echo " No Triplet Found" ,"\n"; } // Driver Code $arr = array (0, -1, 2, -3, 1); $n = sizeof($arr); findTriplets($arr, $n); // This code is contributed by ajit ?> |
Output :
-3 1 2 -1 0 1
Time Complexity : O(n2)
Auxiliary Space : O(1)
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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
- Find triplets in an array whose AND is maximum
- Find all triplets in a sorted array that forms Geometric Progression
- All unique triplets that sum up to a given value
- Print all triplets with given sum
- Print triplets with sum less than or equal to k
- Number of unique triplets whose XOR is zero
- Count triplets with sum smaller than a given value
- Maximum value of XOR among all triplets of an array
- Count Triplets such that one of the numbers can be written as sum of the other two
- Triplets in array with absolute difference less than k
- Sum of special triplets having elements from 3 arrays
- Print all triplets in sorted array that form AP
- Count number of triplets in an array having sum in the range [a, b]
- Count ways to form minimum product triplets



