[Geeks for Geeks] Count triplets with sum smaller than X

Count triplets with sum smaller than X

Given an array arr[] of distinct integers of size N and a value sum, the task is to find the count of triplets (i, j, k), having (i<j<k) with the sum of (arr[i] + arr[j] + arr[k]) smaller than the given value sum.

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