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
[Naive Approach] - By Generating all the pairs- O(n^2) Time and O(1) Space
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.
// C++ program to count pairs whose sum is less
// than given target by generating all the pairs
#include <iostream>
#include <vector>
using namespace std;
int countPairs(vector<int> &arr, int target) {
int cnt = 0;
// Generating all possible pairs
for(int i = 0; i < arr.size(); i++) {
for(int j = i + 1; j < arr.size(); j++) {
// If sum of this pair is less than
// target, then increment the cnt
if(arr[i] + arr[j] < target)
cnt++;
}
}
return cnt;
}
int main() {
vector<int> arr = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
cout << countPairs(arr, target);
return 0;
}
// C program to count pairs whose sum is less
// than given target by generating all the pairs
#include <stdio.h>
int countPairs(int arr[], int n, int target) {
int cnt = 0;
// Generating all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If sum of this pair is less than
// target, then increment the cnt
if (arr[i] + arr[j] < target)
cnt++;
}
}
return cnt;
}
int main() {
int arr[] = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", countPairs(arr, n, target));
return 0;
}
// Java program to count pairs whose sum is less than
// given target by generating all the pairs
class GfG {
static int countPairs(int[] arr, int target) {
int cnt = 0;
// Generating all possible pairs
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
// If sum of this pair is less than
// target, then increment the cnt
if (arr[i] + arr[j] < target)
cnt++;
}
}
return cnt;
}
public static void main(String[] args) {
int[] arr = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
System.out.println(countPairs(arr, target));
}
}
# Python program to count pairs whose sum is less
# than given target by generating all the pairs
def countPairs(arr, target):
cnt = 0
# Generating all possible pairs
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
# If sum of this pair is less than
# target, then increment the cnt
if arr[i] + arr[j] < target:
cnt += 1
return cnt
if __name__ == "__main__":
arr = [2, 1, 8, 3, 4, 7, 6, 5]
target = 7
print(countPairs(arr, target))
// C# program to count pairs whose sum is less
// than given target by generating all the pairs
using System;
class GfG {
static int CountPairs(int[] arr, int target) {
int cnt = 0;
// Generating all possible pairs
for (int i = 0; i < arr.Length; i++) {
for (int j = i + 1; j < arr.Length; j++) {
// If sum of this pair is less than
// target, then increment the cnt
if (arr[i] + arr[j] < target)
cnt++;
}
}
return cnt;
}
static void Main() {
int[] arr = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
Console.WriteLine(CountPairs(arr, target));
}
}
// JavaScript program to count pairs whose sum is less
// than given target by generating all the pairs
function countPairs(arr, target) {
let cnt = 0;
// Generating all possible pairs
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// If sum of this pair is less than
// target, then increment the cnt
if (arr[i] + arr[j] < target)
cnt++;
}
}
return cnt;
}
let arr = [2, 1, 8, 3, 4, 7, 6, 5];
let target = 7;
console.log(countPairs(arr, target));
Output
6
[Better Approach] - Using Binary Search - O(2*nlogn) Time and O(1) Space
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.
// C++ program to count pairs whose sum is less than
// given target using binary search
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Binary search to find lower bound
int binarySearch(vector<int> &arr, int complement) {
int lo = 0, hi = arr.size() - 1;
int res = arr.size();
while(lo <= hi) {
int mid = (lo + hi) / 2;
if(arr[mid] >= complement) {
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
int countPairs(vector<int> &arr, int target) {
int cnt = 0;
// Sort the array to use binary search
sort(arr.begin(), arr.end());
for(int i = 0; i < arr.size(); i++) {
int complement = target - arr[i];
// Index of the element which is greater
// or equal to the complement
int ind = binarySearch(arr, complement);
// arr[i] with make valid pairs with
// each element before the index 'ind'
cnt += ind;
// If element has made a pair with itself
if(ind > i)
cnt--;
}
// Each pair is counted twice
return cnt/2;
}
int main() {
vector<int> arr = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
cout << countPairs(arr, target);
return 0;
}
// C program to count pairs whose sum is less than
// given target using binary search
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
// Binary search to find lower bound
int binarySearch(int arr[], int n, int complement) {
int lo = 0, hi = n - 1;
int res = n;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= complement) {
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
int countPairs(int arr[], int n, int target) {
int cnt = 0;
// Sort the array to use binary search
qsort(arr, n, sizeof(int), (int(*)(const void*, const void*))cmp);
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
// Index of the element which is greater
// or equal to the complement
int ind = binarySearch(arr, n, complement);
// arr[i] will make valid pairs with
// each element before the index 'ind'
cnt += ind;
// If element has made a pair with itself
if (ind > i)
cnt--;
}
// Each pair is counted twice
return cnt / 2;
}
int main() {
int arr[] = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", countPairs(arr, n, target));
return 0;
}
// Java program to count pairs whose sum is less than
// given target using binary search
import java.util.Arrays;
class GfG {
// Binary search to find lower bound
static int binarySearch(int[] arr, int complement) {
int lo = 0, hi = arr.length - 1;
int res = arr.length;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= complement) {
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
static int countPairs(int[] arr, int target) {
int cnt = 0;
// Sort the array to use binary search
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++) {
int complement = target - arr[i];
// Index of the element which is greater
// or equal to the complement
int ind = binarySearch(arr, complement);
// arr[i] will make valid pairs with
// each element before the index 'ind'
cnt += ind;
// If element has made a pair with itself
if (ind > i)
cnt--;
}
// Each pair is counted twice
return cnt / 2;
}
public static void main(String[] args) {
int[] arr = { 2, 1, 8, 3, 4, 7, 6, 5 };
int target = 7;
System.out.println(countPairs(arr, target));
}
}
# Python program to count pairs whose sum is
# less than given target using binary search
# Binary Search to find lower bound
def binarySearch(arr, complement):
lo, hi = 0, len(arr) - 1
res = len(arr)
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] >= complement:
res = mid
hi = mid - 1
else:
lo = mid + 1
return res
def countPairs(arr, target):
cnt = 0
# Sort the array to use binary search
arr.sort()
for i in range(len(arr)):
complement = target - arr[i]
# Index of the element which is greater
# or equal to the complement
ind = binarySearch(arr, complement)
# arr[i] will make valid pairs with
# each element before the index 'ind'
cnt += ind
# If element has made a pair with itself
if ind > i:
cnt -= 1
# Each pair is counted twice
return cnt // 2
if __name__ == "__main__":
arr = [2, 1, 8, 3, 4, 7, 6, 5]
target = 7
print(countPairs(arr, target))
// C# program to count pairs whose sum is less than
// given target using binary search
using System;
class GfG {
// Binary search to find lower bound
static int binarySearch(int[] arr, int complement) {
int lo = 0, hi = arr.Length - 1;
int res = arr.Length;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= complement) {
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
static int countPairs(int[] arr, int target) {
int cnt = 0;
// Sort the array to use binary search
Array.Sort(arr);
for (int i = 0; i < arr.Length; i++) {
int complement = target - arr[i];
// Index of the element which is greater
// or equal to the complement
int ind = binarySearch(arr, complement);
// arr[i] will make valid pairs with
// each element before the index 'ind'
cnt += ind;
// If element has made a pair with itself
if (ind > i)
cnt--;
}
// Each pair is counted twice
return cnt / 2;
}
static void Main() {
int[] arr = { 2, 1, 8, 3, 4, 7, 6, 5 };
int target = 7;
Console.WriteLine(countPairs(arr, target));
}
}
// JavaScript program to count pairs whose sum is less than
// given target using binary search
// Binary search to find lower bound
function binarySearch(arr, complement) {
let lo = 0, hi = arr.length - 1;
let res = arr.length;
while (lo <= hi) {
let mid = Math.floor((lo + hi) / 2);
if (arr[mid] >= complement) {
res = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return res;
}
function countPairs(arr, target) {
let cnt = 0;
// Sort the array to use binary search
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
let complement = target - arr[i];
// Index of the element which is greater
// or equal to the complement
let ind = binarySearch(arr, complement);
// arr[i] will make valid pairs with
// each element before the index 'ind'
cnt += ind;
// If element has made a pair with itself
if (ind > i)
cnt--;
}
// Each pair is counted twice
return Math.floor(cnt / 2);
}
const arr = [2, 1, 8, 3, 4, 7, 6, 5];
const target = 7;
console.log(countPairs(arr, target));
Output
6
[Expected Approach] - Using Two Pointers Technique - O(n*logn+n) Time and O(1) Space
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:
- If sum < target:
Pairs formed by the element at the left pointer with every element between left and right (inclusive) will have a sum less than the target. Therefore, we add (right - left) to the count and move the left pointer one step to the right to explore more pairs. - If sum >= target:
We move the right pointer one step to the left to reduce the sum.
// C++ program to count pairs with sum less
// than target using two pointers technique
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int countPairs(vector<int> &arr, int target) {
// Sort the array to use two pointer technique
sort(arr.begin(), arr.end());
int left = 0, right = arr.size() - 1;
int cnt = 0;
// Two pointer technique
while(left < right) {
int sum = arr[left] + arr[right];
// If the sum is less than target, then arr[left]
// will form a valid pair with every element
// from index left + 1 to right.
if (sum < target) {
cnt += right-left;
left++;
}
else {
right--;
}
}
return cnt;
}
int main() {
vector<int> arr = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
cout << countPairs(arr, target);
return 0;
}
// C program to count pairs with sum less
// than target using two pointers technique
#include <stdio.h>
// Comparator function for qsort
int cmp(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int countPairs(int arr[], int n, int target) {
// Sort the array to use two pointer technique
qsort(arr, n, sizeof(int), cmp);
int left = 0, right = n - 1;
int cnt = 0;
// Two pointer technique
while (left < right) {
int sum = arr[left] + arr[right];
// If the sum is less than target, then arr[left]
// will form a valid pair with every element
// from index left + 1 to right.
if (sum < target) {
cnt += right - left;
left++;
}
else {
right--;
}
}
return cnt;
}
int main() {
int arr[] = {2, 1, 8, 3, 4, 7, 6, 5};
int target = 7;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", countPairs(arr, n, target));
return 0;
}
// Java program to count pairs with sum less
// than target using two pointers technique
import java.util.Arrays;
class GfG {
static int countPairs(int[] arr, int target) {
// Sort the array to use two pointer technique
Arrays.sort(arr);
int left = 0, right = arr.length - 1;
int cnt = 0;
// Two pointer technique
while (left < right) {
int sum = arr[left] + arr[right];
// If the sum is less than target, then arr[left]
// will form a valid pair with every element
// from index left + 1 to right.
if (sum < target) {
cnt += right - left;
left++;
}
else {
right--;
}
}
return cnt;
}
public static void main(String[] args) {
int[] arr = { 2, 1, 8, 3, 4, 7, 6, 5 };
int target = 7;
System.out.println(countPairs(arr, target));
}
}
# Python program to count pairs with sum less
# than target using two pointers technique
def countPairs(arr, target):
# Sort the array to use two pointer technique
arr.sort()
left, right = 0, len(arr) - 1
cnt = 0
# Two pointer technique
while left < right:
sum = arr[left] + arr[right]
# If the sum is less than target, then arr[left]
# will form a valid pair with every element
# from index left + 1 to right.
if sum < target:
cnt += right - left
left += 1
else:
right -= 1
return cnt
if __name__ == "__main__":
arr = [2, 1, 8, 3, 4, 7, 6, 5]
target = 7
print(countPairs(arr, target))
// C# program to count pairs with sum less
// than target using two pointers technique
using System;
class GfG {
static int countPairs(int[] arr, int target) {
// Sort the array to use two pointer technique
Array.Sort(arr);
int left = 0, right = arr.Length - 1;
int cnt = 0;
// Two pointer technique
while (left < right) {
int sum = arr[left] + arr[right];
// If the sum is less than target, then arr[left]
// will form a valid pair with every element
// from index left + 1 to right.
if (sum < target) {
cnt += right - left;
left++;
}
else {
right--;
}
}
return cnt;
}
static void Main() {
int[] arr = { 2, 1, 8, 3, 4, 7, 6, 5 };
int target = 7;
Console.WriteLine(countPairs(arr, target));
}
}
// JavaScript program to count pairs with sum less
// than target using two pointers technique
function countPairs(arr, target) {
// Sort the array to use two pointer technique
arr.sort((a, b) => a - b);
let left = 0, right = arr.length - 1;
let cnt = 0;
// Two pointer technique
while (left < right) {
let sum = arr[left] + arr[right];
// If the sum is less than target, then arr[left]
// will form a valid pair with every element
// from index left + 1 to right.
if (sum < target) {
cnt += right - left;
left++;
}
else {
right--;
}
}
return cnt;
}
const arr = [2, 1, 8, 3, 4, 7, 6, 5];
const target = 7;
console.log(countPairs(arr, target));
Output
6
Related Articles: