880377. Count Pairs in a sorted array whose sum is less than target

Easy

Here is the detailed markdown blog post for the problem "Count Pairs in a sorted array whose sum is less than target":

Count Pairs in a sorted array whose sum is less than target

Summary

Given a sorted integer array and a target value, count all pairs of elements from the array that have a sum less than the target. This problem involves using two-pointer technique to efficiently solve this problem.

Detailed Explanation

To solve this problem, we will use the two-pointer technique. Initialize two pointers, one at the start (i) and another at the end (j). Then, calculate the sum of the values at these positions. If the sum is less than the target, increment i to increase the sum or decrement j to decrease it. Continue this process until i is less than j.

Here's a step-by-step breakdown:

  1. Initialize two pointers i and j such that i starts from the beginning of the array and j starts from the end.
  2. Calculate the sum of the values at positions i and j (arr[i] + arr[j]).
  3. If the sum is less than the target, increment i to increase the sum or decrement j to decrease it.
  4. Continue this process until i is greater than or equal to j.
  5. Count all pairs that satisfy the condition.

Time complexity: O(n), where n is the length of the array. We only need to traverse the array once using two pointers. Space complexity: O(1). We don't use any extra space, as we only keep track of the current positions of the two pointers and the count of pairs that satisfy the condition.

Optimized Solutions

Java

View on GeeksforGeeks
public int countPairs(int[] arr, int target) {
    int i = 0, j = arr.length - 1;
    int count = 0;
    
    while (i < j) {
        int sum = arr[i] + arr[j];
        if (sum < target) {
            i++;
        } else {
            j--;
        }
    }
    
    return j - i;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.