jayati

Find triplets with zero sum

Jan 9th, 2024
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. #include<stdlib.h>
  4. #include<iostream>
  5. using namespace std;
  6.  
  7. // } Driver Code Ends
  8. /* You are required to complete the function below
  9. *  arr[]: input array
  10. *  n: size of array
  11. */
  12. class Solution{
  13.   public:
  14.     //Function to find triplets with zero sum.
  15.    bool findTriplets(int arr[], int n) {
  16.    bool found = false;
  17.  
  18.    sort(arr, arr + n);
  19.  
  20.    for (int i = 0; i < n - 1; i++) {
  21.      int l = i + 1;
  22.      int r = n - 1;
  23.      int x = arr[i];
  24.      while (l < r) {
  25.        if (x + arr[l] + arr[r] == 0) {
  26.  
  27.          l++;
  28.          r--;
  29.          found = true;
  30.          break;
  31.        } else if (x + arr[l] + arr[r] < 0)
  32.          l++;
  33.        else
  34.          r--;
  35.      }
  36.      if (found) break;
  37.    }
  38.  
  39.    return found;
  40.  }
  41. };
  42.  
  43. //{ Driver Code Starts.
  44. int main()
  45. {
  46.     int t;
  47.     cin>>t;
  48.     while(t--){
  49.         int n;
  50.         cin>>n;
  51.         int arr[n]={0};
  52.         for(int i=0;i<n;i++)
  53.             cin>>arr[i];
  54.         Solution obj;
  55.         if(obj.findTriplets(arr, n))
  56.             cout<<"1"<<endl;
  57.         else
  58.             cout<<"0"<<endl;
  59.     }
  60.     return 0;
  61. }
  62. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment