Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2). Examples:
Input : arr[] = {-2, 0, 1, 3}
sum = 2.
Output : 2
Explanation : Below are triplets with sum less than 2
(-2, 0, 1) and (-2, 0, 3)
Input : arr[] = {5, 1, 3, 4, 7}
sum = 12.
Output : 4
Explanation : Below are triplets with sum less than 12
(1, 3, 4), (1, 3, 5), (1, 3, 7) and
(1, 4, 5)
A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and increment count if the triplet sum is smaller than the given sum.
C++
// A Simple C++ program to count triplets with sum smaller
// than a given value
#include <bits/stdc++.h>
usingnamespacestd;
intcountTriplets(intarr[], intn, intsum)
{
// Initialize result
intans = 0;
// Fix the first element as A[i]
for(inti = 0; i < n - 2; i++) {
// Fix the second element as A[j]
for(intj = i + 1; j < n - 1; j++) {
// Now look for the third number
for(intk = j + 1; k < n; k++)
if(arr[i] + arr[j] + arr[k] < sum)
ans++;
}
}
returnans;
}
// Driver program
intmain()
{
intarr[] = { 5, 1, 3, 4, 7 };
intn = sizeofarr / sizeofarr[0];
intsum = 12;
cout << countTriplets(arr, n, sum) << endl;
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// A Simple C program to count triplets with sum smaller
// than a given value
#include <stdio.h>
intcountTriplets(intarr[], intn, intsum)
{
// Initialize result
intans = 0;
// Fix the first element as A[i]
for(inti = 0; i < n - 2; i++) {
// Fix the second element as A[j]
for(intj = i + 1; j < n - 1; j++) {
// Now look for the third number
for(intk = j + 1; k < n; k++)
if(arr[i] + arr[j] + arr[k] < sum)
ans++;
}
}
returnans;
}
// Driver program
intmain()
{
intarr[] = { 5, 1, 3, 4, 7 };
intn = sizeofarr / sizeofarr[0];
intsum = 12;
printf("%d\n", countTriplets(arr, n, sum));
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// A Simple Java program to count triplets with sum smaller
# A Simple Python 3 program to count triplets with sum smaller
# than a given value
#include<bits/stdc++.h>
defcountTriplets(arr, n, sum):
# Initialize result
ans =0
# Fix the first element as A[i]
fori inrange( 0,n-2):
# Fix the second element as A[j]
forj inrange( i+1,n-1):
# Now look for the third number
fork inrange( j+1, n):
if(arr[i] +arr[j] +arr[k] < sum):
ans+=1
returnans
# Driver program
arr =[5, 1, 3, 4, 7]
n =len(arr)
sum=12
print(countTriplets(arr, n, sum))
#Contributed by Smitha
C#
// A Simple C# program to count triplets with sum smaller
// than a given value
usingSystem;
classTest
{
staticint[] arr = newint[]{5, 1, 3, 4, 7};
staticintcountTriplets(intn, intsum)
{
// Initialize result
intans = 0;
// Fix the first element as A[i]
for(inti = 0; i < n-2; i++)
{
// Fix the second element as A[j]
for(intj = i+1; j < n-1; j++)
{
// Now look for the third number
for(intk = j+1; k < n; k++)
if(arr[i] + arr[j] + arr[k] < sum)
ans++;
}
}
returnans;
}
// Driver method to test the above function
publicstaticvoidMain()
{
intsum = 12;
Console.Write(countTriplets(arr.Length, sum));
}
}
Javascript
<script>
// A Simple Javascript program to count triplets with sum smaller
// than a given value
let arr = [5, 1, 3, 4, 7];
functioncountTriplets(n,sum)
{
// Initialize result
let ans = 0;
// Fix the first element as A[i]
for(let i = 0; i < n-2; i++)
{
// Fix the second element as A[j]
for(let j = i + 1; j < n-1; j++)
{
// Now look for the third number
for(let k = j + 1; k < n; k++)
if(arr[i] + arr[j] + arr[k] < sum)
ans++;
}
}
returnans;
}
// Driver method to test the above function
let sum = 12;
document.write(countTriplets(arr.length, sum));
// This code is contributed by avanitrachhadiya2155
</script>
Output:
4
Time Complexity: O(n3) Auxiliary Space: O(1)
An Efficient Solution can count triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop.
1) Sort the input array in increasing order.
2) Initialize result as 0.
3) Run a loop from i = 0 to n-2. An iteration of this loop finds all
triplets with arr[i] as first element.
a) Initialize other two elements as corner elements of subarray
arr[i+1..n-1], i.e., j = i+1 and k = n-1
b) Move j and k toward each other until they meet, i.e., while (j<k),
(i) If arr[i] + arr[j] + arr[k] >= sum
then k--
// Else for current i and j, there can (k-j) possible third elements
// that satisfy the constraint.
(ii) Else Do ans += (k - j) followed by j++
Below is the implementation of the above idea.
C++
// C++ program to count triplets with sum smaller than a given value
#include<bits/stdc++.h>
usingnamespacestd;
intcountTriplets(intarr[], intn, intsum)
{
// Sort input array
sort(arr, arr+n);
// Initialize result
intans = 0;
// Every iteration of loop counts triplet with
// first element as arr[i].
for(inti = 0; i < n - 2; i++)
{
// Initialize other two elements as corner elements
// of subarray arr[j+1..k]
intj = i + 1, k = n - 1;
// Use Meet in the Middle concept
while(j < k)
{
// If sum of current triplet is more or equal,
// move right corner to look for smaller values
if(arr[i] + arr[j] + arr[k] >= sum)
k--;
// Else move left corner
else
{
// This is important. For current i and j, there
// can be total k-j third elements.
ans += (k - j);
j++;
}
}
}
returnans;
}
// Driver program
intmain()
{
intarr[] = {5, 1, 3, 4, 7};
intn = sizeofarr / sizeofarr[0];
intsum = 12;
cout << countTriplets(arr, n, sum) << endl;
return0;
}
Java
// A Simple Java program to count triplets with sum smaller
// than a given value
importjava.util.Arrays;
classTest
{
staticintarr[] = newint[]{5, 1, 3, 4, 7};
staticintcountTriplets(intn, intsum)
{
// Sort input array
Arrays.sort(arr);
// Initialize result
intans = 0;
// Every iteration of loop counts triplet with
// first element as arr[i].
for(inti = 0; i < n - 2; i++)
{
// Initialize other two elements as corner elements
# Initialize other two elements as corner elements
# of subarray arr[j+1..k]
j =i +1
k =n-1
# Use Meet in the Middle concept
while(j < k):
# If sum of current triplet is more or equal,
# move right corner to look for smaller values
if(arr[i]+arr[j]+arr[k] >=sum):
k =k-1
# Else move left corner
else:
# This is important. For current i and j, there
# can be total k-j third elements.
ans +=(k -j)
j =j+1
returnans
# Driver program
if__name__=='__main__':
arr =[5, 1, 3, 4, 7]
n =len(arr)
sum=12
print(countTriplets(arr, n, sum))
# This code is contributed by
# Yatin Gupta
C#
// A Simple C# program to count
// triplets with sum smaller
// than a given value
usingSystem;
classGFG
{
staticint[]arr = newint[]{5, 1, 3, 4, 7};
staticintcountTriplets(intn, intsum)
{
// Sort input array
Array.Sort(arr);
// Initialize result
intans = 0;
// Every iteration of loop
// counts triplet with
// first element as arr[i].
for(inti = 0; i < n - 2; i++)
{
// Initialize other two
// elements as corner elements
// of subarray arr[j+1..k]
intj = i + 1, k = n - 1;
// Use Meet in the Middle concept
while(j < k)
{
// If sum of current triplet
// is more or equal, move right
// corner to look for smaller values
if(arr[i] + arr[j] + arr[k] >= sum)
k--;
// Else move left corner
else
{
// This is important. For
// current i and j, there
// can be total k-j third elements.
ans += (k - j);
j++;
}
}
}
returnans;
}
// Driver Code
publicstaticvoidMain()
{
intsum = 12;
Console.Write(countTriplets(arr.Length, sum));
}
}
// This code is contributed by Smitha
Javascript
<script>
// A Simple Javascript program to count triplets with sum smaller
// than a given value
let arr = [5, 1, 3, 4, 7];
functioncountTriplets(n,sum)
{
// Sort input array
arr.sort(function(a,b){returnb-a});
// Initialize result
let ans = 0;
// Every iteration of loop counts triplet with
// first element as arr[i].
for(let i = 0; i < n - 2; i++)
{
// Initialize other two elements as corner elements
// of subarray arr[j+1..k]
let j = i + 1, k = n - 1;
// Use Meet in the Middle concept
while(j < k)
{
// If sum of current triplet is more or equal,
// move right corner to look for smaller values
if(arr[i] + arr[j] + arr[k] >= sum)
k--;
// Else move left corner
else
{
// This is important. For current i and j, there
// can be total k-j third elements.
ans += (k - j);
j++;
}
}
}
returnans;
}
// Driver method to test the above function
let sum = 12;
document.write(countTriplets(arr.length, sum));
// This code is contributed by rag2127
</script>
Output:
4
Time Complexity: O(n2) Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting this solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy