Count triplet with sum smaller than a given value

Pattern: Two pointers

medium

Count triplets with sum below a limit in O(n²). After sorting, when a triplet fits, every smaller right value fits too, so count them all at once.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers and a limit. Count the triplets of three different positions i < j < k whose values add up to strictly less than limit. For example, [-2, 0, 1, 3] with limit 2 has 2 such triplets: (-2, 0, 1) and (-2, 0, 3). The count is returned as a 64-bit number.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name countTriplets is this guide's own. Since the triplets are counted, not listed, the function may sort the array.

Think first

  • Does sorting change how many triplets there are?
  • With arr[i] fixed, suppose arr[i] + arr[left] + arr[right] is below the limit. What about the same left with any smaller right?
  • If the sum is too big, which pointer must move?

Hints

    Brute force, and why it fails

    Three nested loops test every triplet: O(n³). For 1,000 values that is about 1.7 × 10⁸ triplets, and it gets much worse quickly.

    The key insight

    In a sorted range, one passing triplet proves a whole block of triplets passes. Counting the block with one subtraction turns the inner search into a single two-pointer pass.

    Dry run

    -20i
    01left
    12 
    33right
    count0

    arr = [-2, 0, 1, 3] (already sorted) and limit = 2. Fix i = 0 (value -2), with left = 1 and right = 3.

    Step 1 of 4

    The plan

    sort arr
    count = 0
    for i from 0 to n - 3:
        left = i + 1, right = n - 1
        while left < right:
            if arr[i] + arr[left] + arr[right] < limit:
                count = count + (right - left)
                left = left + 1
            else:
                right = right - 1
    return count
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    Sorting plus n two-pointer passes of O(n) each.

    Edge cases

    • Fewer than three values: 0.
    • [1, 1, 1] with limit 4: 1. With limit 3: 0, because the sum must be strictly smaller.
    • Large counts: n³/6 triplets for large n need a 64-bit count.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long countTriplets(int[] arr, int limit) {
            Arrays.sort(arr);
            int n = arr.length;
            long count = 0;
            for (int i = 0; i < n - 2; i++) {
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    if ((long) arr[i] + arr[left] + arr[right] < limit) {
                        count += right - left;      // arr[left] pairs with every index from left+1 to right
                        left++;
                    } else {
                        right--;
                    }
                }
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        long long countTriplets(vector<int>& arr, int limit) {
            sort(arr.begin(), arr.end());
            int n = static_cast<int>(arr.size());
            long long count = 0;
            for (int i = 0; i < n - 2; i++) {
                int left = i + 1;
                int right = n - 1;
                while (left < right) {
                    if (static_cast<long long>(arr[i]) + arr[left] + arr[right] < limit) {
                        count += right - left;      // arr[left] pairs with every index from left+1 to right
                        left++;
                    } else {
                        right--;
                    }
                }
            }
            return count;
        }
    };

    Python

    class Solution:
        def countTriplets(self, arr, limit):
            arr.sort()
            n = len(arr)
            count = 0
            for i in range(n - 2):
                left, right = i + 1, n - 1
                while left < right:
                    if arr[i] + arr[left] + arr[right] < limit:
                        count += right - left       # arr[left] pairs with every index from left+1 to right
                        left += 1
                    else:
                        right -= 1
            return count

    Common mistakes

    • Adding 1 instead of right - left when the sum fits.
    • Using <= when the problem says strictly smaller.
    • Moving left when the sum is too big, which can miss triplets.

    Similar problems