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++ program to count pairs in an array // whose sum is less than given number x #include<bits/stdc++.h> using namespace std;
// Function to count pairs in array // with sum less than x. int findPairs( int arr[], int n, int x)
{ int l = 0, r = n-1;
int result = 0;
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 l.
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
// Move to smaller value
else
r--;
}
return result;
} // Driven code 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 program to count pairs in an array // whose sum is less than given number x class GFG {
// Function to count pairs in array
// with sum less than x.
static int findPairs( int arr[], int n, int x)
{
int l = 0 , r = n - 1 ;
int result = 0 ;
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 l.
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
// Move to smaller value
else
r--;
}
return result;
}
// Driver method
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));
}
} // This code is contributed by Anant Agarwal. |
# Python3 program to count pairs # in an array whose sum is less # than given number x # Function to count pairs in array # with sum less than x. def findPairs(arr, n, x):
l = 0 ; r = n - 1
result = 0
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 l.
if (arr[l] + arr[r] < x):
result + = (r - l)
l + = 1
# Move to smaller value
else :
r - = 1
return result
# Driver Code arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
n = len (arr)
x = 7
print (findPairs(arr, n, x))
# This code is contributed by Anant Agarwal. |
// C# program to count pairs in // an array whose sum is less // than given number x using System;
class GFG {
// Function to count pairs in array
// with sum less than x.
static int findPairs( int []arr, int n,
int x)
{
int l = 0, r = n - 1;
int result = 0;
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 l.
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
// Move to smaller value
else
r--;
}
return result;
}
// Driver code
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));
}
} // This code is contributed by parashar... |
<script> //javascript program to count pairs in an array // whose sum is less than given number x // Function to count pairs in array // with sum less than x. function findPairs(arr,n,x)
{ let l = 0, r = n-1;
let result = 0;
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 l.
if (arr[l] + arr[r] < x)
{
result += (r - l);
l++;
}
// Move to smaller value
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));
// This code is contributed by vaibhavrabadiya117. </script> |
<?php // PHP program to count pairs in an array // whose sum is less than given number x // Function to count pairs in array // with sum less than x. function findPairs( $arr , $n , $x )
{ $l = 0;
$r = $n - 1;
$result = 0;
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 l.
if ( $arr [ $l ] + $arr [ $r ] < $x )
{
$result += ( $r - $l );
$l ++;
}
// Move to smaller value
else
$r --;
}
return $result ;
} // Driver Code
$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;
// This code is contributed by nitin mittal. ?> |
6
Time complexity : O(n)
Auxiliary Space : O(1)
Using Policy Based Data structure:
Its also works for the unsorted array
#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;
} |
import java.util.*;
public class Main {
// Definition of a SortedSet using the TreeSet class in Java
static class CustomSortedSet {
TreeSet<Map.Entry<Integer, Integer>> set;
public CustomSortedSet() {
// Comparator to sort entries based on the key
Comparator<Map.Entry<Integer, Integer>> comparator =
Comparator.comparingInt(Map.Entry::getKey);
this .set = new TreeSet<>(comparator);
}
// Method to add an entry to the sorted set
public void add(Map.Entry<Integer, Integer> entry) {
set.add(entry);
}
// Method to find the index of the leftmost entry less than the given entry
public int bisectLeft(Map.Entry<Integer, Integer> entry) {
SortedSet<Map.Entry<Integer, Integer>> headSet = new TreeSet<>(set.headSet(entry));
return headSet.size();
}
}
// Function to count pairs in the array whose sum is equal to a given value
static int countPair(List<Integer> v, int targetSum) {
int ans = 0 ; // Initialize a variable to store the count of pairs that sum up
// to the targetSum.
CustomSortedSet sortedSet = new CustomSortedSet(); // Create a CustomSortedSet to
//store entries of values and their
// indices.
int y = 0 ; // Initialize an index variable to keep track of
// the current position in the 'v' list.
// Loop through the 'v' list in reverse order.
for ( int num : v) {
if (sortedSet.set.isEmpty()) {
// If the sortedSet is empty, add the current value and index as the first entry.
sortedSet.add( new AbstractMap.SimpleEntry<>(num, y));
} else {
int left = targetSum - num; // Calculate the value that, when added to 'num',
// equals the targetSum.
ans += sortedSet.bisectLeft( new AbstractMap.SimpleEntry<>(left, - 1 ));
// Use bisectLeft to find the number of entries that sum up to 'left'.
// Increment 'ans' by this count.
sortedSet.add( new AbstractMap.SimpleEntry<>(num, y)); // Add the current value and
// index to the sortedSet.
}
y++; // Increment the index 'y' for the next iteration.
}
return ans; // Return the final count of pairs that sum up to the targetSum.
}
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); // Call the countPair function to calculate the result.
System.out.println(result); // Print the count of pairs that sum up to the targetSum.
}
} |
from sortedcontainers import SortedList
def count_pair(v, target_sum):
ans = 0 # Initialize a variable to store the count of pairs that sum up to the target_sum.
sorted_set = SortedList() # Create a SortedList to store pairs of values and their indices.
y = 0 # Initialize an index variable to keep track of the current position in the 'v' list.
# Loop through the 'v' list in reverse order.
for num in reversed (v):
if not sorted_set:
# If the sorted_set is empty, add the current value and index as the first pair.
sorted_set.add((num, y))
else :
left = target_sum - num # Calculate the value that, when added to 'num', equals the target_sum.
ans + = sorted_set.bisect_left((left, - 1 ))
# Use bisect_left to find the number of pairs that sum up to 'left'.
# Increment 'ans' by this count.
sorted_set.add((num, y)) # Add the current value and index to the sorted_set.
y + = 1 # Increment the index 'y' for the next iteration.
return ans # Return the final count of pairs that sum up to the target_sum.
if __name__ = = "__main__" :
v = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
sum_value = 7
result = count_pair(v, sum_value) # Call the count_pair function to calculate the result.
print (result) # Print the count of pairs that sum up to the target_sum.
|
using System;
using System.Collections.Generic;
class Program
{ static int CountPair(List< int > v, int targetSum)
{
int ans = 0; // Initialize a variable to store the count of pairs
// that sum up to the targetSum.
SortedList< int , int > sortedSet = new SortedList< int , int >(); // Create a SortedList to
// store pairs of values and
// their indices.
int y = 0; // Initialize an index variable to keep track of the current
// position in the 'v' list.
// Loop through the 'v' list in reverse order.
for ( int i = v.Count - 1; i >= 0; i--)
{
int num = v[i];
if (sortedSet.Count == 0)
{
// If the sortedSet is empty, add the current value and index as the first pair.
sortedSet.Add(num, y);
}
else
{
int left = targetSum - num; // Calculate the value that, when added to 'num',
// equals the targetSum.
foreach ( var pair in sortedSet)
{
if (pair.Key >= left)
{
break ;
}
ans++; // Increment 'ans' by this count.
}
sortedSet.Add(num, y); // Add the current value and index to the sortedSet.
}
y++; // Increment the index 'y' for the next iteration.
}
return ans; // Return the final count of pairs that sum up to the targetSum.
}
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); // Call the CountPair function to calculate the result.
Console.WriteLine(result); // Print the count of pairs that sum up to the targetSum.
}
} |
const SortedList = require( 'sortedlist' ); // Import the SortedList library or implement a SortedList data structure.
function countPair(v, targetSum) {
let ans = 0; // Initialize a variable to store the count of pairs that sum up to the targetSum.
const sortedSet = new SortedList(); // Create a SortedList to store pairs of values and their indices.
let y = 0; // Initialize an index variable to keep track of the current position in the 'v' array.
// Loop through the 'v' array in reverse order.
for (let i = v.length - 1; i >= 0; i--) {
const num = v[i];
if (sortedSet.isEmpty()) {
// If the sortedSet is empty, add the current value and index as the first pair.
sortedSet.add({ value: num, index: y });
} else {
const left = targetSum - num; // Calculate the value that, when added to 'num', equals the targetSum.
ans += sortedSet.bisectLeft({ value: left, index: -1 });
// Use bisectLeft to find the number of pairs that sum up to 'left'.
// Increment 'ans' by this count.
sortedSet.add({ value: num, index: y }); // Add the current value and index to the sortedSet.
}
y++; // Increment the index 'y' for the next iteration.
}
return ans; // Return the final count of pairs that sum up to the targetSum.
} const v = [1, 2, 3, 4, 5, 6, 7, 8]; const sumValue = 7; const result = countPair(v, sumValue); // Call the countPair function to calculate the result.
console.log(result); // Print the count of pairs that sum up to the targetSum.
|
6
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.
#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;
// Iterate over the vector in reverse order
for ( int i = v.size() - 1; i >= 0; i--) {
int num = v[i];
if (st.empty()) {
st[num] = y;
} else {
int left = sum - num;
// Count the number of elements less than or equal to 'left' in the map
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;
} |
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 ;
// Iterate over the ArrayList in reverse order
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;
// Count the number of elements less than 'left' in the TreeMap
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));
}
} |
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 ))
|
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;
// Iterate over the list in reverse order
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;
// Count the number of elements less than 'left' in the dictionary
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));
}
} // This code is contributed by shivamgupta0987654321 |
function countPair(v, sum) {
let ans = 0;
let st = new Map();
let y = 0;
// Iterate over the array in reverse order
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;
// Count the number of elements less than or equal to 'left' in the map
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)); |
6
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 .