Suppose we have an array of n integers called nums and we also have a target, we have to find the number of index triplets (i, j, k) here i, j, k all are in range 0 to n - 1 and that satisfy the condition nums[i] + nums[j] + nums[k] < target.
So, if the input is like nums = [-2,0,1,3], and target = 2, then the output will be 2, as there are two triplets which sums are less than 2: [-2,0,1] and [-2,0,3].
To solve this, we will follow these steps −
ret := 0
sort the array a
n := size of a
for initialize i := 0, when i < n - 2, update (increase i by 1), do −
left := i + 1, right := n - 1
while left < right, do −
sum := a[i] + a[left] + a[right]
if sum < t, then −
ret := ret + right - left
(increase left by 1)
Otherwise
(decrease right by 1)
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int threeSumSmaller(vector<int<& a, int t) {
int ret = 0;
sort(a.begin(), a.end());
int n = a.size();
for (int i = 0; i < n - 2; i++) {
int left = i + 1;
int right = n - 1;
while (left < right) {
int sum = a[i] + a[left] + a[right];
if (sum < t) {
ret += right - left;
left++;
}
else
right--;
}
}
return ret;
}
};
main(){
Solution ob;
vector<int< v = {-2,0,1,3};
cout << (ob.threeSumSmaller(v,2));
}Input
[-2,0,1,3] 2
Output
2