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
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:
- Run three nested loops with loop counter i, j, k
- 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.
- 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<bits/stdc++.h>usingnamespacestd;// Prints all triplets in arr[] with 0 sumvoidfindTriplets(intarr[],intn){boolfound =true;for(inti=0; i<n-2; i++){for(intj=i+1; j<n-1; j++){for(intk=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 arrayif(found ==false)cout <<" not exist "<<endl;}// Driver codeintmain(){intarr[] = {0, -1, 2, -3, 1};intn =sizeof(arr)/sizeof(arr[0]);findTriplets(arr, n);return0;}chevron_rightfilter_noneJava
// A simple Java program to find three elements// whose sum is equal to zeroclassnum{// Prints all triplets in arr[] with 0 sumstaticvoidfindTriplets(int[] arr,intn){booleanfound =true;for(inti=0; i<n-2; i++){for(intj=i+1; j<n-1; j++){for(intk=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 arrayif(found ==false)System.out.println(" not exist ");}// Driver codepublicstaticvoidmain(String[] args){intarr[] = {0, -1,2, -3,1};intn =arr.length;findTriplets(arr, n);}}//This code is contributed by//Smitha Dinesh Semwalchevron_rightfilter_nonePython3
# A simple Python 3 program# to find three elements whose# sum is equal to zero# Prints all triplets in# arr[] with 0 sumdeffindTriplets(arr, n):found=Trueforiinrange(0, n-2):forjinrange(i+1, n-1):forkinrange(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 arrayif(found==False):print(" not exist ")# Driver codearr=[0,-1,2,-3,1]n=len(arr)findTriplets(arr, n)# This code is contributed by Smitha Dinesh Semwalchevron_rightfilter_noneC#
// A simple C# program to find three elements// whose sum is equal to zerousingSystem;classGFG {// Prints all triplets in arr[] with 0 sumstaticvoidfindTriplets(int[]arr,intn){boolfound =true;for(inti = 0; i < n-2; i++){for(intj = i+1; j < n-1; j++){for(intk = 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// arrayif(found ==false)Console.Write(" not exist ");}// Driver codepublicstaticvoidMain(){int[]arr = {0, -1, 2, -3, 1};intn = arr.Length;findTriplets(arr, n);}}// This code is contributed by nitin mittal.chevron_rightfilter_nonePHP
<?php// A simple PHP program to// find three elements whose// sum is equal to zero// Prints all triplets// in arr[] with 0 sumfunctionfindTriplets($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 arrayif($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?>chevron_rightfilter_none
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.
- Time Complexity : O(n3).
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:
- Create a hashap to store a key value pair.
- Run a nested loop with two loops, outer loop from 0 to n-2 and the inner loop from i+1 to n-1
- Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or not
- 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<bits/stdc++.h>usingnamespacestd;// function to print triplets with 0 sumvoidfindTriplets(intarr[],intn){boolfound =false;for(inti=0; i<n-1; i++){// Find all pairs with sum equals to// "-arr[i]"unordered_set<int> s;for(intj=i+1; j<n; j++){intx = -(arr[i] + arr[j]);if(s.find(x) != s.end()){printf("%d %d %d\n", x, arr[i], arr[j]);found =true;}elses.insert(arr[j]);}}if(found ==false)cout <<" No Triplet Found"<< endl;}// Driver codeintmain(){intarr[] = {0, -1, 2, -3, 1};intn =sizeof(arr)/sizeof(arr[0]);findTriplets(arr, n);return0;}chevron_rightfilter_noneJava
// Java program to find triplets in a given// array whose sum is zeroimportjava.util.*;classGFG{// function to print triplets with 0 sumstaticvoidfindTriplets(intarr[],intn){booleanfound =false;for(inti =0; i < n -1; i++){// Find all pairs with sum equals to// "-arr[i]"HashSet<Integer> s =newHashSet<Integer>();for(intj = i +1; j < n; j++){intx = -(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 codepublicstaticvoidmain(String[] args){intarr[] = {0, -1,2, -3,1};intn = arr.length;findTriplets(arr, n);}}// This code contributed by Rajput-Jichevron_rightfilter_nonePython3
# Python3 program to find triplets# in a given array whose sum is zero# function to print triplets with 0 sumdeffindTriplets(arr, n):found=Falseforiinrange(n-1):# Find all pairs with sum# equals to "-arr[i]"s=set()forjinrange(i+1, n):x=-(arr[i]+arr[j])ifxins:print(x, arr[i], arr[j])found=Trueelse:s.add(arr[j])iffound==False:print("No Triplet Found")# Driver Codearr=[0,-1,2,-3,1]n=len(arr)findTriplets(arr, n)# This code is contributed by Shrikant13chevron_rightfilter_noneC#
// C# program to find triplets in a given// array whose sum is zerousingSystem;usingSystem.Collections.Generic;classGFG{// function to print triplets with 0 sumstaticvoidfindTriplets(int[]arr,intn){boolfound =false;for(inti = 0; i < n - 1; i++){// Find all pairs with sum equals to// "-arr[i]"HashSet<int> s =newHashSet<int>();for(intj = i + 1; j < n; j++){intx = -(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 codepublicstaticvoidMain(String[] args){int[]arr = {0, -1, 2, -3, 1};intn = arr.Length;findTriplets(arr, n);}}// This code has been contributed by 29AjayKumarchevron_rightfilter_none
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.
- Time Complexity: O(n2).
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:
- Sort the array in ascending order.
- Traverse the array from start to end.
- For every index i, create two variables l = i + 1 and r = n – 1
- 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
- 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]
- 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<bits/stdc++.h>usingnamespacestd;// function to print triplets with 0 sumvoidfindTriplets(intarr[],intn){boolfound =false;// sort array elementssort(arr, arr+n);for(inti=0; i<n-1; i++){// initialize left and rightintl = i + 1;intr = n - 1;intx = arr[i];while(l < r){if(x + arr[l] + arr[r] == 0){// print elements if it's sum is zeroprintf("%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 leftelseif(x + arr[l] + arr[r] < 0)l++;// if sum is greater than zero than// decrement in right sideelser--;}}if(found ==false)cout <<" No Triplet Found"<< endl;}// Driven sourceintmain(){intarr[] = {0, -1, 2, -3, 1};intn =sizeof(arr)/sizeof(arr[0]);findTriplets(arr, n);return0;}chevron_rightfilter_noneJava
// Java program to find triplets in a given// array whose sum is zeroimportjava.util.Arrays;importjava.io.*;classGFG {// function to print triplets with 0 sumstaticvoidfindTriplets(intarr[],intn){booleanfound =false;// sort array elementsArrays.sort(arr);for(inti=0; i<n-1; i++){// initialize left and rightintl = i +1;intr = n -1;intx = arr[i];while(l < r){if(x + arr[l] + arr[r] ==0){// print elements if it's sum is zeroSystem.out.print(x +" ");System.out.print(arr[l]+" ");System.out.println(arr[r]+" ");l++;r--;found =true;}// If sum of three elements is less// than zero then increment in leftelseif(x + arr[l] + arr[r] <0)l++;// if sum is greater than zero than// decrement in right sideelser--;}}if(found ==false)System.out.println(" No Triplet Found");}// Driven sourcepublicstaticvoidmain (String[] args) {intarr[] = {0, -1,2, -3,1};intn =arr.length;findTriplets(arr, n);}//This code is contributed by Tushil..}chevron_rightfilter_nonePython3
# python program to find triplets in a given# array whose sum is zero# function to print triplets with 0 sumdeffindTriplets(arr, n):found=False# sort array elementsarr.sort()foriinrange(0, n-1):# initialize left and rightl=i+1r=n-1x=arr[i]while(l < r):if(x+arr[l]+arr[r]==0):# print elements if it's sum is zeroprint(x, arr[l], arr[r])l+=1r-=1found=True# If sum of three elements is less# than zero then increment in leftelif(x+arr[l]+arr[r] <0):l+=1# if sum is greater than zero than# decrement in right sideelse:r-=1if(found==False):print(" No Triplet Found")# Driven sourcearr=[0,-1,2,-3,1]n=len(arr)findTriplets(arr, n)# This code is contributed by Smitha Dinesh Semwalchevron_rightfilter_noneC#
// C# program to find triplets in a given// array whose sum is zerousingSystem;publicclassGFG{// function to print triplets with 0 sumstaticvoidfindTriplets(int[]arr,intn){boolfound =false;// sort array elementsArray.Sort(arr);for(inti=0; i<n-1; i++){// initialize left and rightintl = i + 1;intr = n - 1;intx = arr[i];while(l < r){if(x + arr[l] + arr[r] == 0){// print elements if it's sum is zeroConsole.Write(x +" ");Console.Write(arr[l]+" ");Console.WriteLine(arr[r]+" ");l++;r--;found =true;}// If sum of three elements is less// than zero then increment in leftelseif(x + arr[l] + arr[r] < 0)l++;// if sum is greater than zero than// decrement in right sideelser--;}}if(found ==false)Console.WriteLine(" No Triplet Found");}// Driven sourcestaticpublicvoidMain (){int[]arr = {0, -1, 2, -3, 1};intn =arr.Length;findTriplets(arr, n);}//This code is contributed by akt_mit..}chevron_rightfilter_nonePHP
<?php// PHP program to find// triplets in a given// array whose sum is zero// function to print// triplets with 0 sumfunctionfindTriplets($arr,$n){$found= false;// sort array elementssort($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 zeroecho$x," ",$arr[$l]," ",$arr[$r],"\n";$l++;$r--;$found= true;}// If sum of three elements// is less than zero then// increment in leftelseif($x+$arr[$l] +$arr[$r] < 0)$l++;// if sum is greater than// zero than decrement// in right sideelse$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?>chevron_rightfilter_none
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.
- Time Complexity : O(n2).
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.
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:
- Number of unique triplets whose XOR is zero
- Print all triplets with given sum
- All unique triplets that sum up to a given value
- Find all triplets in a sorted array that forms Geometric Progression
- Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
- Minimum steps to make sum and the product of all elements of array non-zero
- Rearrange array to make sum of all subarrays starting from first index non-zero
- Print all triplets in sorted array that form AP
- Maximum value of XOR among all triplets of an array
- Count triplets with sum smaller than a given value
- Print triplets with sum less than k
- Sum of special triplets having elements from 3 arrays
- Count number of triplets in an array having sum in the range [a, b]
- 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 triplets such that sum of any two number is equal to third | Set 2
- Maximize sum of array by reducing array elements to contain no triplets (i, j, k) where a[i] < a[j] and a[i] < a[k] and j <i < k
- Find triplets in an array whose AND is maximum
- Find number of triplets in array such that a[i]>a[j]>a[k] and i<j<k
- Make all elements zero by decreasing any two elements by one at a time

