Open In App

C++ Program to 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   

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

Below is the implementation of the above approach: 






// 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 = 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)
                {
                    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;
}

Output
0 -1 1
2 -3 1

Complexity Analysis: 

 
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: 

  1. Create a hashmap to store a key-value pair.
  2. 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
  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.

Below is the implementation of the above approach: 




// 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
", 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;
}

Output
-1 0 1
-3 2 1

Complexity Analysis: 

 
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[i], array[l] and array[r] is equal to zero then print the triplet and break the loop
  5. 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]
  6. 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] .

Below is the implementation of the above approach: 




// 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
", x, arr[l], arr[r]);
                l++;
                r--;
                found = true;
                  break;
            }
  
            // 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;
}

Output
-3 1 2
-1 0 1

Complexity Analysis: 

 

Please refer complete article on Find all triplets with zero sum for more details!


Article Tags :