-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathFind triplets with zero sum
54 lines (52 loc) · 1.07 KB
/
Find triplets with zero sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<bits/stdc++.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
// } Driver Code Ends
/* 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 a[], int n)
{
//Your code here
sort(a,a+n);
for(int i = 0 ; i < n - 2 ; i++)
{
int l = i+1;
int r = n - 1;
while(l<r){
int sum = a[i] + a[l] + a[r];
if(sum == 0)
return true;
else if(sum > 0)
r--;
else
l++;
}
}
return false;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n]={0};
for(int i=0;i<n;i++)
cin>>arr[i];
Solution obj;
if(obj.findTriplets(arr, n))
cout<<"1"<<endl;
else
cout<<"0"<<endl;
}
return 0;
} // } Driver Code Ends