Java Program to Find all triplets with zero sum

06 Jan, 2022
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 runs 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, kThe first 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.
Run three nested loops with loop counter i, j, kThe first 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.
Run three nested loops with loop counter i, j, k
The first 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.
Below is the implementation of the above approach: 
Java
// A simple Java program to find three elements// whose sum is equal to zeroclass num{// Prints all triplets in arr[] with 0 sumstatic void findTriplets(int[] arr, int n){    boolean found = false;    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("");                    found = true;                }            }        }    }      // If no triplet with 0 sum found in array    if (found == false)        System.out.println(" not exist ");  }  // Driver codepublic 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
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 space 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 pair sum and can be solved in O(n) time using hashing.
Algorithm: 
Create a hashmap to store a key-value pair.Run a nested loop with two loops, the outer loop from 0 to n-2 and the inner loop from i+1 to n-1Check if the sum of ith and jth element multiplied with -1 is present in the hashmap or notIf the element is present in the hashmap, print the triplet else insert the j’th element in the hashmap.
Create a hashmap to store a key-value pair.
Run a nested loop with two loops, the 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.
Below is the implementation of the above approach: 
Java
// Java program to find triplets in a given// array whose sum is zeroimport 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<Integer> s = new HashSet<Integer>();            for (int j = i + 1; j < n; j++)             {                int x = -(arr[i] + arr[j]);                if (s.contains(x))                 {                    System.out.printf("%d %d %d", x, arr[i], arr[j]);                    found = true;                }                 else                 {                    s.add(arr[j]);                }            }        }          if (found == false)        {            System.out.printf(" No Triplet Found");        }    }      // 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
-1 0 1
-3 2 1
Complexity Analysis: 
Time Complexity: O(n2). Since two nested loops are required, so the time complexity is O(n2).
Auxiliary Space: O(n). Since a hashmap is required, so the space 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: 
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 – 1Run a loop until l is less than r if the sum of array[i], array[l] and array[r] is equal to zero then print the triplet and break the loopIf the sum is less than zero then increment the value of l, by increasing the 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 the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].
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[i], array[l] and array[r] is equal to zero then print the triplet and break the loop
If the sum is less than zero then increment the value of l, by increasing the 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 the value of r, by increasing the value of l the sum will decrease as the array is sorted, so array[r-1] < array [r].
Below is the implementation of the above approach: 
Java
// Java  program to find triplets in a given// array whose sum is zeroimport java.util.Arrays; import java.io.*;  class GFG {    // function to print triplets with 0 sumstatic void findTriplets(int arr[], int n){    boolean found = false;      // 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] == 0)            {                // print elements if it's sum is zero                    System.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 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)            System.out.println(" No Triplet Found");}  // Driven source    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 Tushil..    }
-3 1 2
-1 0 1
Complexity Analysis: 
Time Complexity : O(n2). Only two nested loops are required, so the time complexity is O(n2).
Auxiliary Space : O(1), no extra space is required, so the time complexity is constant.
Please refer complete article on Find all triplets with zero sum for more details!
Facebook
Google
two-pointer-algorithm
Arrays
Hash
Java
Java Programs
Searching
Sorting
Google
Facebook
two-pointer-algorithm
Arrays
Searching
Hash
Sorting
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Sort string of characters