[Geeks for Geeks] Find triplets with zero sum

Find triplets with zero sum

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

  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
public:
//Function to find triplets with zero sum.
bool findTriplets(int arr[], int n)
{
sort(arr, arr + n);
for(int i = 0; i < n; i++) {
int l = i + 1, r = n - 1;
while(l < r) {
int sum = arr[l] + arr[r];
if(sum > -arr[i]) r--;
else if(sum < -arr[i]) l++;
else return 1;
}
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/find-triplets-with-zero-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.