Question:
How to Find triplets with zero sum?

Summary:

Suppose we have an array of n integers. Through the below C++ code, we will check whether the array contains a triplet that sums up to zero. 


Solution:

/* You are required to complete the function below

*  arr[]: input array

*  n: size of array

*/

class Solution{

  public:

    //Function to find triplets with zero sum.

     bool findTriplets(int arr[], int n)

    { 

        //Your code here

        sort(arr,arr+n);

        for(int i = 0; i < n-2; i++){

            int l = i+1, r = n-1;

            

            while(l < r) {

                int sum = arr[i]+arr[l]+arr[r];

                 if(sum > 0){

                     r--;

                 }

                 else{

                     l++;

                 }

                 if(sum == 0){

                     return 1;

                    

                 }

                 

            }

            

        }

        return 0;

    }

};


Explenation:


  • Initially, the input array arr is sorted in ascending order using sort(arr, arr+n).

  • Then, a for loop is used to iterate through the array from the beginning to the second-to-last element (n-2).


Two pointers, l (left) and r (right), are initialized within the loop.

  • l starts one element after the current element i.

  • r starts at the last element of the array.

A while loop is employed to iterate until the left pointer (l) is less than the right pointer (r).

Calculating Sum:


The sum of the current triplet (arr[i] + arr[l] + arr[r]) is calculated.


  • If the sum becomes zero at any point, the function returns 1 (true), indicating the presence of a triplet with a zero sum.

  • If the loop completes without finding such a triplet, the function returns 0 (false).


Answered by: >surajkumaae3j

Credit: >GeekforGeeks


Suggested blogs:

>What is meant by progressive framework?

>Why logged user object is all strings in Vuejs and Laravel 10?

>How to get the date and time and display it in a defineProps in Vuejs?

>Fix error while retrieving pages from a pdf using convert_from_path (pdf2image)

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks


Submit
0 Answers