![]() |
VOOZH | about |
Given an array arr[] and an integer target, the task is to find the count of pairs whose sum is strictly less than given target.
Examples:
Input: arr[] = [7, 2, 5, 3], target = 8
Output: 2
Explanation: There are 2 pairs with sum less than 8: (2, 5) and (2, 3).Input: arr[] = [5, 2, 3, 2, 4, 1], target = 5
Output: 4
Explanation: There are 4 pairs whose sum is less than 5: (2, 2), (2, 1), (3, 1) and (2, 1).Input: arr[] = [2, 1, 8, 3, 4, 7, 6, 5], target = 7
Output: 6
Explanation: There are 6 pairs whose sum is less than 7: (2, 1), (2, 3), (2, 4), (1, 3), (1, 4) and (1, 5).
Table of Content
A simple approach is to generate all possible pairs using two nested for loops and count those pairs whose sum is less than given target.
6
The idea is to first sort the array. For each element we will calculate the complement (target - arr[i]) required to make pair sum equal to the target. Then, find the first element in the array which is greater than or equal (lower bound) to the complement using binary search. All the elements which appear before that element will make a valid pair with current element having sum less than given target. We also need to handle the case where an element pairs with itself. Since, each pair is counted twice, total count divide by two will be our answer.
6
First sort the array, then use Two Pointers Technique to find the number of pairs with a sum less than the given target. Initialize two pointers, one at the beginning (left) and the other at the end (right) of the array. Now, compare the sum of elements at these pointers with the target:
6
Related Articles: