876441. Count Pairs whose sum is less than target
Easy
Count Pairs whose sum is less than target
Slug: count-pairs-whose-sum-is-less-than-target
Difficulty: Easy
Id: 876441
Topic Tags: Sorting, two-pointer-algorithm, Arrays
Company Tags: None
Summary
Given an array of integers and a target value, find the number of pairs in the array whose sum is less than the target. The problem requires sorting the array, then using a two-pointer algorithm to efficiently count the desired pairs.
Detailed Explanation
To solve this problem, we first sort the given array of integers. Then, we initialize two pointers, one at the start and another at the end of the array. We iterate through the array by moving the pointers towards each other based on the sum of the values they are pointing to. If the sum is less than or equal to the target, we increment a counter for each such pair found.
Here's a step-by-step breakdown of the solution:
- Sort the given array in ascending order.
- Initialize two pointers,
startandend, at the start and end of the array respectively. - Iterate through the array by moving the pointers towards each other based on the sum of the values they are pointing to.
- If the sum is less than or equal to the target, increment a counter for each such pair found.
Time complexity: O(n log n) due to sorting Space complexity: O(1)
Optimized Solutions
Java
import java.util.Arrays;
public class Main {
public static int countPairs(int[] arr, int target) {
Arrays.sort(arr);
int start = 0;
int end = arr.length - 1;
int count = 0;
while (start < end) {
if (arr[start] + arr[end] <= target) {
count++;
start++;
end--;
} else if (arr[start] + arr[end] > target) {
end--;
}
}
return count;
}
}