Count pairs in a sorted array whose sum is less than x
Given a sorted integer array and number x, the task is to count pairs in array whose sum is less than x.
Examples:
Input : arr[] = {1, 3, 7, 9, 10, 11}
x = 7
Output : 1
There is only one pair (1, 3)
Input : arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
x = 7
Output : 6
Pairs are (1, 2), (1, 3), (1, 4), (1, 5)
(2, 3) and (2, 4)
A simple solution of this problem run two loops to generate all pairs and one by one and check if current pair’s sum is less than x or not.
An Efficient solution of this problem is take initial and last value of index in l and r variable.
1) Initialize two variables l and r to find the candidate
elements in the sorted array.
(a) l = 0
(b) r = n - 1
2) Initialize : result = 0
2) Loop while l < r.
// If current left and current
// right have sum smaller than x,
// the all elements from l+1 to r
// form a pair with current
(a) If (arr[l] + arr[r] < x)
result = result + (r - l)
l++;
(b) Else
r--;
3) Return result
Below is the implementation of above steps.
C++
#include<bits/stdc++.h>
using namespace std;
int findPairs( int arr[], int n, int x)
{
int l = 0, r = n-1;
int result = 0;
while (l < r)
{
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
else
r--;
}
return result;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof (arr)/ sizeof ( int );
int x = 7;
cout << findPairs(arr, n, x);
return 0;
}
|
Java
class GFG {
static int findPairs( int arr[], int n, int x)
{
int l = 0 , r = n - 1 ;
int result = 0 ;
while (l < r)
{
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
else
r--;
}
return result;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int n = arr.length;
int x = 7 ;
System.out.print(findPairs(arr, n, x));
}
}
|
Python3
def findPairs(arr, n, x):
l = 0 ; r = n - 1
result = 0
while (l < r):
if (arr[l] + arr[r] < x):
result + = (r - l)
l + = 1
else :
r - = 1
return result
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
n = len (arr)
x = 7
print (findPairs(arr, n, x))
|
C#
using System;
class GFG {
static int findPairs( int []arr, int n,
int x)
{
int l = 0, r = n - 1;
int result = 0;
while (l < r)
{
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
else
r--;
}
return result;
}
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6, 7, 8};
int n = arr.Length;
int x = 7;
Console.Write(findPairs(arr, n, x));
}
}
|
Javascript
<script>
function findPairs(arr,n,x)
{
let l = 0, r = n-1;
let result = 0;
while (l < r)
{
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
else
r--;
}
return result;
}
let arr = [1, 2, 3, 4, 5, 6, 7, 8];
let n = arr.length;
let x = 7;
document.write(findPairs(arr,n,x));
</script>
|
PHP
<?php
function findPairs( $arr , $n , $x )
{
$l = 0;
$r = $n - 1;
$result = 0;
while ( $l < $r )
{
if ( $arr [ $l ] + $arr [ $r ] < $x )
{
$result += ( $r - $l );
$l ++;
}
else
$r --;
}
return $result ;
}
$arr = array (1, 2, 3, 4, 5, 6, 7, 8);
$n = sizeof( $arr ) / sizeof( $arr [0]);
$x = 7;
echo findPairs( $arr , $n , $x );
return 0;
?>
|
Time complexity : O(n)
Auxiliary Space : O(1)
Using Policy Based Data structure:
Its also works for the unsorted array
C++
#include <iostream>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set \
tree<pair< int , int >, null_type, less<pair< int , int > >, \
rb_tree_tag, tree_order_statistics_node_update>
int countPair(vector< int > v, int sum)
{
int ans = 0;
ordered_set st;
int y = 0;
for ( auto i = v.rbegin(); i != v.rend(); i++) {
int num = *i;
if (st.empty())
st.insert({ num, y });
else {
int left = sum - num;
ans += st.order_of_key({ left, -1 });
st.insert({ num, y });
}
y++;
}
return ans;
}
int main()
{
int n;
cin >> n;
vector< int > v{ 1, 2, 3, 4, 5, 6, 7, 8 };
int sum = 7;
cout << countPair(v, sum);
return 0;
}
|
Java
import java.util.*;
public class Main {
static class CustomSortedSet {
TreeSet<Map.Entry<Integer, Integer>> set;
public CustomSortedSet() {
Comparator<Map.Entry<Integer, Integer>> comparator =
Comparator.comparingInt(Map.Entry::getKey);
this .set = new TreeSet<>(comparator);
}
public void add(Map.Entry<Integer, Integer> entry) {
set.add(entry);
}
public int bisectLeft(Map.Entry<Integer, Integer> entry) {
SortedSet<Map.Entry<Integer, Integer>> headSet = new TreeSet<>(set.headSet(entry));
return headSet.size();
}
}
static int countPair(List<Integer> v, int targetSum) {
int ans = 0 ;
CustomSortedSet sortedSet = new CustomSortedSet();
int y = 0 ;
for ( int num : v) {
if (sortedSet.set.isEmpty()) {
sortedSet.add( new AbstractMap.SimpleEntry<>(num, y));
} else {
int left = targetSum - num;
ans += sortedSet.bisectLeft( new AbstractMap.SimpleEntry<>(left, - 1 ));
sortedSet.add( new AbstractMap.SimpleEntry<>(num, y));
}
y++;
}
return ans;
}
public static void main(String[] args) {
List<Integer> v = Arrays.asList( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 );
int sumValue = 7 ;
int result = countPair(v, sumValue);
System.out.println(result);
}
}
|
Python3
from sortedcontainers import SortedList
def count_pair(v, target_sum):
ans = 0
sorted_set = SortedList()
y = 0
for num in reversed (v):
if not sorted_set:
sorted_set.add((num, y))
else :
left = target_sum - num
ans + = sorted_set.bisect_left((left, - 1 ))
sorted_set.add((num, y))
y + = 1
return ans
if __name__ = = "__main__" :
v = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
sum_value = 7
result = count_pair(v, sum_value)
print (result)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int CountPair(List< int > v, int targetSum)
{
int ans = 0;
SortedList< int , int > sortedSet = new SortedList< int , int >();
int y = 0;
for ( int i = v.Count - 1; i >= 0; i--)
{
int num = v[i];
if (sortedSet.Count == 0)
{
sortedSet.Add(num, y);
}
else
{
int left = targetSum - num;
foreach ( var pair in sortedSet)
{
if (pair.Key >= left)
{
break ;
}
ans++;
}
sortedSet.Add(num, y);
}
y++;
}
return ans;
}
static void Main( string [] args)
{
List< int > v = new List< int > { 1, 2, 3, 4, 5, 6, 7, 8 };
int sumValue = 7;
int result = CountPair(v, sumValue);
Console.WriteLine(result);
}
}
|
Javascript
const SortedList = require( 'sortedlist' );
function countPair(v, targetSum) {
let ans = 0;
const sortedSet = new SortedList();
let y = 0;
for (let i = v.length - 1; i >= 0; i--) {
const num = v[i];
if (sortedSet.isEmpty()) {
sortedSet.add({ value: num, index: y });
} else {
const left = targetSum - num;
ans += sortedSet.bisectLeft({ value: left, index: -1 });
sortedSet.add({ value: num, index: y });
}
y++;
}
return ans;
}
const v = [1, 2, 3, 4, 5, 6, 7, 8];
const sumValue = 7;
const result = countPair(v, sumValue);
console.log(result);
|
Time complexity : O(n)
Auxiliary Space : O(n)
Using SortedDict class from the sortedcontainers library in Python:
Steps:
- Import the SortedDict class from the sortedcontainers library.
- Define the countPair function that takes a list of integers v and an integer sum as inputs.
- Iterate over the elements of v in reverse order using the reversed() function.
- If st is empty, insert the current element and its index into st using the setitem() method.
- Otherwise, compute the value of left as the difference between sum and the current element.
- Compute the number of elements in st that are less than left using the bisect_left() method, and add it to ans.
- Insert the current element and its index into st using the setitem() method.
- Increment the value of y. Return the value of ans.
C++
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int countPair(vector< int >& v, int sum) {
int ans = 0;
map< int , int > st;
int y = 0;
for ( int i = v.size() - 1; i >= 0; i--) {
int num = v[i];
if (st.empty()) {
st[num] = y;
} else {
int left = sum - num;
ans += distance(st.begin(), st.lower_bound(left));
st[num] = y;
}
y++;
}
return ans;
}
int main() {
vector< int > v = {1, 2, 3, 4, 5, 6, 7, 8};
int sum = 7;
cout << countPair(v, sum) << endl;
return 0;
}
|
Java
import java.util.*;
public class Program {
static int countPair(ArrayList<Integer> v, int sum) {
int ans = 0 ;
TreeMap<Integer, Integer> st = new TreeMap<>();
int y = 0 ;
for ( int i = v.size() - 1 ; i >= 0 ; i--) {
int num = v.get(i);
if (st.isEmpty()) {
st.put(num, y);
} else {
int left = sum - num;
for (Map.Entry<Integer, Integer> entry : st.entrySet()) {
if (entry.getKey() < left) {
ans++;
}
}
st.put(num, y);
}
y++;
}
return ans;
}
public static void main(String[] args) {
ArrayList<Integer> v = new ArrayList<>(Arrays.asList( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ));
int sum = 7 ;
System.out.println(countPair(v, sum));
}
}
|
Python
from sortedcontainers import SortedDict
def countPair(v, sum ):
ans = 0
st = SortedDict()
y = 0
for num in reversed (v):
if not st:
st[num] = y
else :
left = sum - num
ans + = st.bisect_left(left)
st[num] = y
y + = 1
return ans
v = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
sum = 7
print (countPair(v, sum ))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int CountPair(List< int > v, int sum)
{
int ans = 0;
Dictionary< int , int > st = new Dictionary< int , int >();
int y = 0;
for ( int i = v.Count - 1; i >= 0; i--)
{
int num = v[i];
if (st.Count == 0)
{
st[num] = y;
}
else
{
int left = sum - num;
foreach ( var kvp in st)
{
if (kvp.Key < left)
{
ans++;
}
}
st[num] = y;
}
y++;
}
return ans;
}
static void Main( string [] args)
{
List< int > v = new List< int > { 1, 2, 3, 4, 5, 6, 7, 8 };
int sum = 7;
Console.WriteLine(CountPair(v, sum));
}
}
|
Javascript
function countPair(v, sum) {
let ans = 0;
let st = new Map();
let y = 0;
for (let i = v.length - 1; i >= 0; i--) {
let num = v[i];
if (st.size === 0) {
st.set(num, y);
} else {
let left = sum - num;
st.forEach((value, key) => {
if (key < left) {
ans++;
}
});
st.set(num, y);
}
y++;
}
return ans;
}
let v = [1, 2, 3, 4, 5, 6, 7, 8];
let sum = 7;
console.log(countPair(v, sum));
|
Extension:
If array is unsorted, then we can sort the array first and then apply above method to solve in O(n Log n) time and Auxiliary Space required = O(n), where n represents the size of the given array.
Related Articles:
Count all distinct pairs with difference equal to k
Count pairs with given sum
This article is contributed by DANISH_RAZA .
Last Updated :
09 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...