880377. Count Pairs in a sorted array whose sum is less than target
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:
- Initialize two pointers i and j such that i starts from the beginning of the array and j starts from the end.
- Calculate the sum of the values at positions i and j (arr[i] + arr[j]).
- 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 greater than or equal to j.
- 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
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;
}