problem no 68 : find the triplet inside array whose sum is zero.

Find triplets with zero sum 
Basic Accuracy: 48.42% Submissions: 96881 Points: 1

Given an array of integers. Check whether it contains a triplet that sums up to zero. 

Example 1:

Input: n = 5, arr[] = {0, -1, 2, -3, 1}
Output: 1
Explanation: 0, -1 and 1 forms a triplet
with sum equal to 0.

Example 2:

Input: n = 3, arr[] = {1, 2, 3}
Output: 0
Explanation: No triplet with zero sum exists. 


Your Task:

You don't need to read input or print anything. Your task is to complete the boolean function findTriplets() which takes the array arr[] and the size of the array (n) as inputs and print 1 if the function returns true else print false if the function return false. 





code:

 bool findTriplets(int arr[], int n)

    { 

         int found=0;

         int l,r;

         sort(arr,arr+n);

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

         {

             l=i+1;

             r=n-1;

             while(r>l)

             {

                 

                 if(arr[i]+arr[l]+arr[r]==0)

                 {

                     found=1;

                     break;

                 }

                 if(arr[i]+arr[r]+arr[l]<0)

                 {

                     l++;

                 }

                 if(arr[i]+arr[r]+arr[l]>0)

                 {

                     r--;

                 }

                 

                 

             }

             if(found==1)

             {

                 break;

             }

         }

         return found;

       

    }


 

Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.