VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-triplets-with-sum-smaller-than-a-given-value/

⇱ Count triplets with sum smaller than a given value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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)

[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. 


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


Output
2
Comment
Article Tags: