Count triplets with sum smaller than a given value

Last Updated : 19 Apr, 2026

Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value.

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)

Try It Yourself
redirect icon

[Brute Force Approach] Using Loops - O(n^3) Time and O(1) Space

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++
#include <iostream>
#include <vector>
using namespace std;

int countTriplets(int sum, vector<int> &arr)
{
    int n = arr.size();
    int ans = 0;

    // Fix the first element as A[i]
    for (int i = 0; i < n - 2; i++) {
        
        // Fix the second element as A[j]
        for (int j = i + 1; j < n - 1; j++) {
            
            // Now look for the third number
            for (int k = j + 1; k < n; k++)
                if (arr[i] + arr[j] + arr[k] < sum)
                    ans++;
        }
    }
    return ans;
}

// Driver code
int main()
{
    vector<int> arr = { -2, 0, 1, 3 };
    int sum = 2;
    cout << countTriplets(sum, arr) << endl;
    return 0;
}
C
#include <stdio.h>

int countTriplets(int sum, int arr[], int n)
{
    int ans = 0;

    // Fix the first element as A[i]
    for (int i = 0; i < n - 2; i++) {
        // Fix the second element as A[j]
        for (int j = i + 1; j < n - 1; j++) {
            // Now look for the third number
            for (int k = j + 1; k < n; k++)
                if (arr[i] + arr[j] + arr[k] < sum)
                    ans++;
        }
    }
    return ans;
}

// Driver code
int main()
{
    int arr[] = { -2, 0, 1, 3 };
    int sum = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", countTriplets(sum, arr, n));
    return 0;
}
Java
class GfG
{
    static int countTriplets(int sum, int[] arr)
    {
        int n = arr.length;
        int ans = 0;

        for (int i = 0; i < n - 2; i++)
            for (int j = i + 1; j < n - 1; j++)
                for (int k = j + 1; k < n; k++)
                    if (arr[i] + arr[j] + arr[k] < sum)
                        ans++;

        return ans;
    }
    // Driver code
    public static void main(String[] args) 
    {
        int[] arr = {-2, 0, 1, 3};
        int sum = 2;

        System.out.println(countTriplets(sum, arr));
    }
}
Python
def countTriplets(sum ,arr):

    n = len(arr)
    ans = 0

    # Fix the first element as A[i]
    for i in range( 0 ,n-2):
    
        # Fix the second element as A[j]
        for j in range( i+1 ,n-1):
    
            # Now look for the third number
            for k in range( j+1, n):
                if (arr[i] + arr[j] + arr[k] < sum):
                    ans+=1
    
    return ans

# Driver code
if __name__ == '__main__':
    arr = [-2, 0, 1, 3]
    sum = 2
    print(countTriplets(sum, arr))
C#
using System;

class GfG
{
    static int CountTriplets(int sum, int[] arr)
    {
        int n = arr.Length;
        int count = 0;

        // Fix the first element as A[i]
        for (int i = 0; i < n - 2; i++)
        {
            // Fix the second element as A[j]
            for (int j = i + 1; j < n - 1; j++)
            {
                // Now look for the third number
                for (int k = j + 1; k < n; k++)
                {
                    if (arr[i] + arr[j] + arr[k] < sum)
                        count++;
                }
            }
        }

        return count;
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { -2, 0, 1, 3 };
        int sum = 2;

        Console.WriteLine(CountTriplets(sum, arr));
    }
}
JavaScript
function countTriplets(sum, arr)
{
    let n = arr.length
    let ans = 0;

    // Fix the first element as arr[i]
    for (let i = 0; i < n - 2; i++) {
        // Fix the second element as arr[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++;
        }
    }
    return ans;
}

// Driver code
let arr = [ -2, 0, 1, 3 ];
let sum = 2;
console.log(countTriplets(sum, arr));

Output
2

[Efficient Approach] Using Two Pointer Technique - O(n^2) Time and O(1) Space

Sorting the array first and then, then using the two pointer technique in a loop gives in efficient solution that count triplets in O(n^2)

Step 1: Sort the input array in increasing order.
Step 2: Initialize result as 0.
Step 3: Run a loop from i = 0 to n-2, where each iteration finds all triplets with arr[i] as the first element

a. Initialize the j = i+1 and k = n - 1, as the corner elements of the subarray arr[i+1..n-1].

b. Move j and k toward each other until they meet, i.e., while j < k:

c. If arr[i] + arr[j] + arr[k] >= sum: k-- to reduce the sum.

Else (arr[i] + arr[j] + arr[k] < sum): All elements between j and k also form valid triplets so count them all at once and increment j

Dry run: arr[] = {-2,0, 1, 3}, sum = 2

  • For index i=0. j = 1 and k = 3 then ans = -2+0+3 = 1, 1 < 2: ans += (k-j) = 2, then j++
    j = 2, k = 3 then sum = -2 + 1 + 3 = 2, 2 >=2 , then k--
    j = 2, k = 2 now j < k
    -> exit
  • For index i=1. j = 2 and k = 3 then ans = 0+1+3 =4, 4 >= 2 then k--
    j = 2, k = 2 then j<k
    -> exit

Final ans = 2

C++
#include <iostream>
#include <vector>
using namespace std;

int countTriplets(int sum, vector<int> &arr)
{
    // Sort input array
    int n = arr.size();
    sort(arr.begin(), arr.end());
    // Initialize result
    int ans = 0;

    // Every iteration of loop counts triplet with
    // first element as arr[i].
    for (int i = 0; i < n - 2; i++)
    {
        // Initialize other two elements as corner elements
        // of subarray arr[j+1..k]
        int 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++;
            }
        }
    }
    return ans;
}

int main()
{
    vector<int> arr = {-2, 0, 1, 3};
    int sum = 2;
    cout << countTriplets(sum, arr) << endl;
    return 0;
}
Java
import java.util.Arrays;

class GfG
{
    static int countTriplets(int sum, int[] arr)
    {
        int n = arr.length;
        Arrays.sort(arr);
     
        int ans = 0;
     
        // Every iteration of loop counts triplet with
        // first element as arr[i].
        for (int i = 0; i < n - 2; i++)
        {
            // Initialize other two elements as corner elements
            // of subarray arr[j+1..k]
            int 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
                {
                    // For current i and j, there
                    // can be total k-j third elements.
                    ans += (k - j);
                    j++;
                }
            }
        }
        return ans;
    }
    
    
    public static void main(String[] args)
    {
        int arr[] = new int[]{-2, 0, 1, 3};
        int sum = 2;
        System.out.println(countTriplets(sum, arr));
    }
}
Python
def countTriplets(sum, arr):

    # Sort input array
    n = len(arr)
    arr.sort()

    ans = 0

    # Every iteration of loop counts triplet with
    # first element as arr[i].
    for i in range(0, n - 2):

        # 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:

                # For current i and j, there
                # can be total k-j third elements.
                ans += (k - j)
                j = j + 1

    return ans


# Driver code
if __name__ == '__main__':
    arr = [-2, 0, 1, 3]
    sum = 2
    print(countTriplets(sum, arr))
C#
using System;

class GfG
{
    
    static int countTriplets(int sum, int[] arr)
    {
        // Sort input array
        int n = arr.Length;
        Array.Sort(arr);
    
        // Initialize result
        int ans = 0;
    
        // Every iteration of loop
        // counts triplet with
        // first element as arr[i].
        for (int i = 0; i < n - 2; i++)
        {
            // Initialize other two 
            // elements as corner elements
            // of subarray arr[j+1..k]
            int 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++;
                }
            }
        }
        return ans;
    }
    
    public static void Main() 
    {
        int []arr = new int[]{-2, 0, 1, 3};
        int sum = 2; 
        Console.Write(countTriplets(sum, arr));
    }
}
JavaScript
function countTriplets(sum, arr)
{

    let n = arr.length;
    // Sort input array
    arr.sort(function(a, b) { return a - b });

    // 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++;
            }
        }
    }
    return ans;
}

// Driver code
let arr = [ -2, 0, 1, 3 ];
let sum = 2;
console.log(countTriplets(sum, arr));

Output
2
Comment