Triplets with sum with given range | Practice | GeeksforGeeks

Given an array Arr[] of N distinct integers and a range from L to R, the task is to count the number of triplets having a sum in the range [L, R].

Example 1:
Input:
N = 4
Arr = {8 , 3, 5, 2}
L = 7, R = 11
Output: 1
Explaination: There is only one triplet {2, 3, 5}
having sum 10 in range [7, 11].

Example 2:
Input:
N = 5
Arr = {5, 1, 4, 3, 2}
L = 2, R = 7
Output: 2
Explaination: There two triplets having 
sum in range [2, 7] are {1,4,2} and {1,3,2}.

Your Task:
You don't need to read input or print anything. Your task is to complete the function countTriplets() which takes the array Arr[] and its size N and L and R as input parameters and returns the count.

Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 103
1 ≤ Arr[i] ≤ 103
1 ≤ L ≤ R ≤ 109
+3
kaustubhdwivedi17295 months ago
Approach :
Step1 : Find triplets having sum < L   =   C1
Step2 : Find triplets having sum > R   =  C2
Step3 : Find Total Possible triplets   =   N*(N-1)*(N-2) / 6
Step4 : Find answer =    Total - (C1+ C2) 
Calculating C1

    int findSmallerthan(int arr[], int n, int L){
        int count = 0;
        for(int i = 0; i < n; i++){
            int j = i+1, k = n-1;
            while(j < k){
                int sum = arr[i] + arr[j] + arr[k];
                if(sum < L){
                    count += k - j;
                    j++;
                }
                if(sum >= L){
                    k--;
                }
            }
        }
        return count;
    }
 
 
Calculating C2
int findGreaterthan(int arr[], int n, int R){
        int count = 0;
        for(int i = 0; i < n; i++){
            int j = i+1, k = n-1;
            while(j < k){
                int sum = arr[i] + arr[j] + arr[k];
                if(sum > R){
                    count += k - j;
                    k--;
                }
                if(sum <= R){
                    j++;
                }
            }
        }
        return count;
    }
0
sourabhch13315 months ago
similar codeforces que: https://codeforces.com/problemset/problem/1538/C
0
ududu7
This comment was deleted.
+2
mastermind_5 months ago
( C++ ) 2 Pointers Shorter Solution, ~ O(N*N) Time , O(1) Space
int countTriplets(int arr[], int n, int L, int R) {
    sort(arr, arr + n);
    auto func = [&](int k) {
        int cnt = 0;
        for (int i = 0; i < n; i++) {
            int l = i + 1, r = n - 1;
            while (l < r) {
                if (arr[i] + arr[l] + arr[r] > k)r--;
                else cnt += r - l, l++;
            }
        }
        return cnt;
    };
    return func(R) - func(L - 1);
}
+8
abhishekshyam5 months ago
Idea behind solutions: 
Find triplets lesser than or equal to R Find triplets lesser than or equal to L-1Subtract both to get number of triplets desired 
Find triplets lesser than or equal to R 
Find triplets lesser than or equal to L-1
Subtract both to get number of triplets desired 
Approach: 
Make function to find all triplets lesser than or equal to certain target say tar. Sorting is necessary for the same. Solve triplets having particular sum problem, and alter the same. One thing that is different is when sum≤tar , we increase count by r-l. Take an example, 1 2 3 4 , l points to = 2, r points to = 4. For this pair say we are finding lesser than 6, Now sum 2+4=> 6, so we reach conclusion that 1 2 4 makes a triplet. But notice that 1 2 3 also makes a triplet lesser than given value, which we want. r-l => 4-2 = 2  solves the issue of redoing that part and we can move l by +1. If sum greater than given values, just r--.
Make function to find all triplets lesser than or equal to certain target say tar. Sorting is necessary for the same. 
Solve triplets having particular sum problem, and alter the same. One thing that is different is when sum≤tar , we increase count by r-l. Take an example, 1 2 3 4 , l points to = 2, r points to = 4. For this pair say we are finding lesser than 6, Now sum 2+4=> 6, so we reach conclusion that 1 2 4 makes a triplet. But notice that 1 2 3 also makes a triplet lesser than given value, which we want. r-l => 4-2 = 2  solves the issue of redoing that part and we can move l by +1. 
If sum greater than given values, just r--.
Intuition:  
The trick for return countLesserEqual(Arr,N,R) - countLesserEqual(Arr,N,L-1); must be known.Finding triplets for sum must be known.
The trick for return countLesserEqual(Arr,N,R) - countLesserEqual(Arr,N,L-1); must be known.
Finding triplets for sum must be known.
 
Complexity: O(n^2) time, O(1) space
class Solution {
  public:
    int countLesserEqual(int Arr[], int N, int tar)
    {
        int c=0;
        for(int i=0;i<N-1;i++)
        {
            int l=i+1;
            int r=N-1;
            while(l<r)
            {
                int sum = Arr[i]+Arr[l]+Arr[r];
                if(sum <= tar)
                {
                    c+=r-l;
                    l++;
                }
                else
                {
                    r--;
                }
            }
        }
        // cout<<c<<endl;
        return c;
    }
    
    int countTriplets(int Arr[], int N, int L, int R) {
        
        sort(Arr,Arr+N);
        return countLesserEqual(Arr,N,R) - countLesserEqual(Arr,N,L-1);
        
    }
};
 
0
soumyaranjansatapathy5 months ago
this is JAVA solution
 
class Solution {   public static int countTripletsLessThan(int[] arr, int n, int val) {             Arrays.sort(arr);
              int ans = 0;
       int j, k;
           int sum;
              for (int i = 0; i < n - 2; i++) {
           j = i + 1;           k = n - 1;
                    while (j != k) {               sum = arr[i] + arr[j] + arr[k];
                              if (sum > val) k--;
                             else {                   ans += (k - j);                   j++;               }           }       }
       return ans;   }
      public static int countTriplets(int arr[], int n, int a, int b) {
             int res;
              res = countTripletsLessThan(arr, n, b) -             countTripletsLessThan(arr, n, a - 1);
       return res;   }} 
+5
udaytyagi01235 months ago
int count(int Arr[],int N,int value)   {       if(N<2)          return 0;       sort(Arr,Arr+N);       int count=0;       for(int i=0;i<N-2;i++)       {           int low=i+1;           int high=N-1;           while(low<high)           {               int target=Arr[i]+Arr[low]+Arr[high];               if(target>value)               {                   high--;               }               else               {                   count=count+(high-low);                   low++;               }           }       }       return count;   }   int countTriplets(int Arr[], int N, int L, int R) {       int left=count(Arr,N,L-1);       int right=count(Arr,N,R);       return right-left;   }
+1
manojkanakala4445 months ago
C++ code 
int count(int arr[],int n,int val)
    {
        sort(arr,arr+n);
        int ans=0;
        for(int i=0;i<n-2;i++)
        {
            int j=i+1;
            int k=n-1;
            while(j!=k)
            {
                int sum = arr[i]+arr[j]+arr[k];
                if(sum>val)
                k--;
                else
                {
                    ans += (k-j);
                    j++;
                }
            }
        }
        return ans;
    }
    int countTriplets(int arr[], int n, int L, int R) {
        // code here
        int x = count(arr,n,R);
        int y = count(arr,n,L-1);
        return x-y;
    }
0
rajn149646 months ago
int helper(int arr[],int n,int x) {     sort(arr,arr+n);     int count=0;     for(int i=n-1;i>=2;i--)     {         int a=0,b=i-1;         while(a<b)         {             if(arr[a]+arr[b]+arr[i]>x)               b--;           else               {                   count=count+b-a;                   a++;               }         }     }     return count; }    int countTriplets(int arr[], int N, int L, int R) {       // code here       fact(N);       return(helper(arr,N,R)-helper(arr,N,L-1));        fact(N);   }
0
Himanshu Sahu9 months ago
Himanshu Sahu
Java Solution
class Solution {    static int countTriplets(int arr[], int n, int L, int R) {        Arrays.sort(arr);        return countSum(arr,n,R) - countSum(arr,n,L-1);    }        static int countSum(int[] arr,int n,int final_sum){        int count = 0;        for(int i =0;i<n-2;i++){ int="" left="i+1;" int="" right="n-1;" while(left="" <="" right)="" {="" int="" sum="arr[i]" +="" arr[left]="" +="" arr[right];="" if(sum=""> final_sum){                     right--;                }else {                    count += (right-left);                    left++;                }                }        }                return count;    }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.