882859. Count all triplets with given sum in sorted array

Medium

Here is a detailed Markdown blog post for the problem "Count all triplets with given sum in sorted array":

Count all triplets with given sum in sorted array

Summary

Given an array of integers, count the number of triplets that have a specific sum. The array is already sorted.

This problem involves using the two-pointer algorithm and hash to solve the problem efficiently. The key concept involved is finding pairs of elements that add up to a certain value.

Detailed Explanation

To solve this problem, we will use the two-pointer technique along with a hash set to keep track of the elements we have seen so far.

Here's the step-by-step breakdown:

  1. Initialize three pointers: i, j and k. All are initially at the start of the array.
  2. Initialize a variable count to store the count of triplets that sum up to the target value.
  3. Iterate through the array with pointer i.
  4. For each element, calculate the target value minus the current element (target - arr[i]). This will be our target sum for the remaining elements.
  5. Use pointer j to find the first occurrence of this target sum in the hash set. If we haven't seen this sum before, add it to the hash set and move j to the next element.
  6. Move pointer k until we have found a pair that sums up to the target value minus the current element (arr[j] + arr[k] == target - arr[i]). The number of such pairs is equal to the count of triplets that sum up to the target value.
  7. Increment the count variable by the count of triplets and move all three pointers.

Time complexity: O(n^2) Space complexity: O(n)

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class CountTriplets {
    public static int countTriplets(int[] arr, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int count = 0;
        
        for (int i = 0; i < arr.length; i++) {
            int targetSum = target - arr[i];
            if (map.containsKey(targetSum)) {
                int jIndex = map.get(targetSum);
                while (jIndex < i) {
                    count += jIndex + 1;
                    jIndex++;
                }
            } else {
                map.put(arr[i], i);
            }
        }
        
        return count;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.