Number of indices pair such that element pair sum from first Array is greater than second Array
Last Updated :
12 Jul, 2025
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.
Examples:
Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3}
Output: 7
Explanation:
There are a total of 7 pairs of indices {i, j} in the array following the condition. They are:
{0, 1}: A[0] + A[1] > B[0] + B[1]
{0, 3}: A[0] + A[3] > B[0] + B[3]
{1, 2}: A[1] + A[2] > B[1] + B[2]
{1, 3}: A[1] + A[3] > B[1] + B[3]
{1, 4}: A[1] + A[4] > B[1] + B[4]
{2, 3}: A[2] + A[3] > B[2] + B[3]
{3, 4}: A[3] + A[4] > B[3] + B[4]
Input: A[] = {1, 3, 2, 4}, B[] = {1, 3, 2, 4}
Output: 0
Explanation:
No such possible pairs of {i, j} can be found that satisfies the given condition
Naive Approach: The naive approach is to consider all the possible pairs of {i, j} in the given arrays and check if A[i] + A[j] > B[i] + B[j]. This can be done by using the concept of nested loops.
Time Complexity: O(N2)
Implementation:-
C++
// C++ program to find the number of indices pair
// such that pair sum from first Array
// is greater than second Array
#include <bits/stdc++.h>
using namespace std;
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
int getPairs(vector<int> A, vector<int> B, int n)
{
//variable to store answer
int ans=0;
//iterating over array
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
//if found such element then increase answer
if(A[i]+A[j]>B[i]+B[j])ans++;
}
}
return ans;
}
// Driver code
int main()
{
//size of array A and B
int n = 5;
vector<int> A;
vector<int> B;
A.push_back(4);
A.push_back(8);
A.push_back(2);
A.push_back(6);
A.push_back(2);
B.push_back(4);
B.push_back(5);
B.push_back(4);
B.push_back(1);
B.push_back(3);
cout << getPairs(A, B, n);
return 0;
}
//code contributed by shubhamrajput6156
Java
// Java program to find the number of indices pair such that
// pair sum from first Array is greater than second Array
import java.util.*;
public class Main {
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
public static int getPairs(int[] A, int[] B, int n)
{
// variable to store answer
int ans = 0;
// iterating over array
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++) {
// if found such element then increase
// answer
if (A[i] + A[j] > B[i] + B[j])
ans++;
}
}
return ans;
}
// Driver code
public static void main(String[] args)
{
// size of array A and B
int n = 5;
int[] A = { 4, 8, 2, 6, 2 };
int[] B = { 4, 5, 4, 1, 3 };
System.out.println(getPairs(A, B, n));
}
}
Python3
# Python 3 program to find the number of indices pair
# such that pair sum from first Array
# is greater than second Array
# Function to get the number of pairs of indices
# {i, j} in the given two arrays A and B such that
# A[i] + A[j] > B[i] + B[j]
def getPairs(A, B, n):
# variable to store answer
ans = 0
for i in range(n - 1):
for j in range(i + 1, n):
# if found such element then increase answer
if A[i] + A[j] > B[i] + B[j]:
ans += 1
return ans
#driver code
n=5
A = []
A.append(4)
A.append(8)
A.append(2)
A.append(6)
A.append(2)
B = []
B.append(4)
B.append(5)
B.append(4)
B.append(1)
B.append(3)
print(getPairs(A, B, n))
# This code is contributed by redmoonz.
C#
// C# program to find the number of indices pair such that
// pair sum from first Array is greater than second Array
using System;
using System.Collections.Generic;
public class GFG {
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
static int GetPairs(List<int> A, List<int> B, int n)
{
// variable to store answer
int ans = 0;
// iterating over array
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// if found such element then increase
// answer
if (A[i] + A[j] > B[i] + B[j]) {
ans++;
}
}
}
return ans;
}
// Driver code
static public void Main(string[] args)
{
// size of array A and B
int n = 5;
List<int> A = new List<int>{ 4, 8, 2, 6, 2 };
List<int> B = new List<int>{ 4, 5, 4, 1, 3 };
Console.WriteLine(GetPairs(A, B, n));
}
}
// This Code is Contributed by Prasad Kandekar(prasad264)
JavaScript
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
function getPairs(A, B, n)
{
// variable to store answer
let ans = 0;
// iterating over array
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
// if found such element then increase answer
if (A[i] + A[j] > B[i] + B[j])
ans++;
}
}
return ans;
}
// Driver code
function main()
{
// size of array A and B
let n = 5;
let A = [ 4, 8, 2, 6, 2 ];
let B = [ 4, 5, 4, 1, 3 ];
console.log(getPairs(A, B, n));
}
main();
Output:- 7
Time Complexity:- O(N^2)
Space Complexity:- O(1)
Efficient Approach: The key observation from the problem is that the given condition can also be visualised as (ai-bi) + (aj-bj)> 0 so we can make another array to store the difference of both arrays. let this array be D . Therefore, the problem reduces to finding pairs with Di+Dj>0. Now we can sort D array and for each corresponding element Di we will find the no of good pairs that Di can make and add this no of pairs to a count variable.For each element Di to find the no of good pairs it can make we can use the upper_bound function of the standard template library to find the upper bound of -Di. since the array is sorted so all elements present after -Di will also make good pair with Di .thus,if upper bound of -Di is x and n be the total size of array then total pairs corresponding to Di will be n-x. This approach takes O(NlogN) time.
- The given condition in the question can be rewritten as:
A[i] + A[j] > B[i] + B[j]
A[i] + A[j] - B[i] - B[j] > 0
(A[i] - B[i]) + (A[j] - B[j]) > 0
- Create another array, say D, to store the difference between elements at the corresponding index in both array, i.e.
- If we carefully look at the last condition ( (A[i] - B[i]) + (A[j] - B[j]) > 0 ) then it is quite obvious that the given condition i<j is trivial and non significant. Therefore, now we only have to find pairs in D such that their sum is > 0.
D[i] = A[i] - B[i]
- Now to make sure that the constraint i < j is satisfied, sort the difference array D, so that each element i is smaller than elements to its right.
- If at some index i, the value in the difference array D is negative, then we only need to find the nearest position 'j' at which the value is just greater than -D[i], so that on summation the value becomes > 0.
Inorder to find such index 'j', upper_bound() function or Binary Search can be used, since the array is sorted. - If at some index i, the value in array D is positive, then that means all the values after it will be positive as well. Therefore total no. of pair from index i to n-1 will be equal to n-i-1.
Below is the implementation of the above approach:
C++
// C++ program to find the number of indices pair
// such that pair sum from first Array
// is greater than second Array
#include <bits/stdc++.h>
using namespace std;
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
int getPairs(vector<int> A, vector<int> B, int n)
{
// Initializing the difference array D
vector<int> D(n);
// Computing the difference between the
// elements at every index and storing
// it in the array D
for (int i = 0; i < n; i++) {
D[i] = A[i] - B[i];
}
// Sort the array D
sort(D.begin(), D.end());
// Variable to store the total
// number of pairs that satisfy
// the given condition
long long total = 0;
// Loop to iterate through the difference
// array D and find the total number
// of pairs of indices that follow the
// given condition
for (int i = 0; i < n; ++i) {
// If the value at that index is negative or zero
// then we need to find the index of the
// value just greater than -D[i]
if (D[i] <= 0) {
int k = upper_bound(D.begin(), D.end(), -D[i])
- D.begin();
total += n - k;
}
// If the value at the index is positive
// then we need to find the number of indexes after i-th index
else {
total += n-i-1;
}
}
return total;
}
// Driver code
int main()
{
int n = 5;
vector<int> A;
vector<int> B;
A.push_back(4);
A.push_back(8);
A.push_back(2);
A.push_back(6);
A.push_back(2);
B.push_back(4);
B.push_back(5);
B.push_back(4);
B.push_back(1);
B.push_back(3);
cout << getPairs(A, B, n);
}
// This code is contributed by Udit Mehta
Java
// Java program to find the number of indices pair
// such that pair sum from first Array
// is greater than second Array
import java.util.*;
class GFG{
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
static long getPairs(Vector<Integer> A, Vector<Integer> B, int n)
{
// Initializing the difference array D
int []D = new int[n];
// Computing the difference between the
// elements at every index and storing
// it in the array D
for (int i = 0; i < n; i++)
{
D[i] = A.get(i) - B.get(i);
}
// Sort the array D
Arrays.sort(D);
// Variable to store the total
// number of pairs that satisfy
// the given condition
long total = 0;
// Loop to iterate through the difference
// array D and find the total number
// of pairs of indices that follow the
// given condition
for (int i = 0; i < n; ++i) {
// If the value at that index is negative or zero
// then we need to find the index of the
// value just greater than -D[i]
if (D[i] <= 0) {
int k = upper_bound(D,0,D.length, -D[i]);
total += n - k;
}
// If the value at the index is positive
// then we need to find the number of indexes after i-th index
else {
total += n-i-1;
}
}
return total;
}
static int upper_bound(int[] a, int low,
int high, int element)
{
while(low < high){
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver code
public static void main(String[] args)
{
int n = 5;
Vector<Integer> A = new Vector<Integer>();
Vector<Integer> B= new Vector<Integer>();
A.add(4);
A.add(8);
A.add(2);
A.add(6);
A.add(2);
B.add(4);
B.add(5);
B.add(4);
B.add(1);
B.add(3);
System.out.print(getPairs(A, B, n));
}
}
// This code is contributed by Udit Mehta
Python3
# Python 3 program to find the number of indices pair
# such that pair sum from first Array
# is greater than second Array
import bisect
# Function to get the number of pairs of indices
# {i, j} in the given two arrays A and B such that
# A[i] + A[j] > B[i] + B[j]
def getPairs(A, B, n):
# Initializing the difference array D
D = [0]*(n)
# Computing the difference between the
# elements at every index and storing
# it in the array D
for i in range(n):
D[i] = A[i] - B[i]
# Sort the array D
D.sort()
# Variable to store the total
# number of pairs that satisfy
# the given condition
total = 0
# Loop to iterate through the difference
# array D and find the total number
# of pairs of indices that follow the
# given condition
for i in range(0,n):
# If the value at that index is negative
# then we need to find the index of the
# value just greater than -D[i]
if(D[i] <= 0):
k = bisect.bisect_right(D, -D[i], 0, len(D))
total += n - k
# If the value at the index i is positive,
# then we need to find the number of indexes after i-th index
else:
total += n-i-1
return total
# Driver code
if __name__ == "__main__":
n = 5
A = []
B = []
A.append(4);
A.append(8);
A.append(2);
A.append(6);
A.append(2);
B.append(4);
B.append(5);
B.append(4);
B.append(1);
B.append(3);
print(getPairs(A, B, n))
# This code is contributed by Udit Mehta
C#
// C# program to find the number of indices pair
// such that pair sum from first Array
// is greater than second Array
using System;
using System.Collections.Generic;
class GFG{
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
static long getPairs(List<int> A, List<int> B, int n)
{
// Initializing the difference array D
int []D = new int[n];
// Computing the difference between the
// elements at every index and storing
// it in the array D
for (int i = 0; i < n; i++)
{
D[i] = A[i] - B[i];
}
// Sort the array D
Array.Sort(D);
// Variable to store the total
// number of pairs that satisfy
// the given condition
long total = 0;
// Loop to iterate through the difference
// array D and find the total number
// of pairs of indices that follow the
// given condition
for (int i = 0; i < n; ++i) {
// If the value at that index is negative or zero
// then we need to find the index of the
// value just greater than -D[i]
if (D[i] <= 0) {
int k = upper_bound(D,0,D.Length, -D[i]);
total += n - k;
}
// If the value at the index is positive
// then we need to find the number of indexes after i-th index
else {
total += n-i-1;
}
}
return total;
}
static int upper_bound(int[] a, int low,
int high, int element)
{
while(low < high){
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver code
public static void Main(String[] args)
{
int n = 5;
List<int> A = new List<int>();
List<int> B= new List<int>();
A.Add(4);
A.Add(8);
A.Add(2);
A.Add(6);
A.Add(2);
B.Add(4);
B.Add(5);
B.Add(4);
B.Add(1);
B.Add(3);
Console.Write(getPairs(A, B, n));
}
}
// This code is contributed by Udit Mehta
JavaScript
<script>
// Javascript program to find the number of indices pair
// such that pair sum from first Array
// is greater than second Array
// Function to get the number of pairs of indices
// {i, j} in the given two arrays A and B such that
// A[i] + A[j] > B[i] + B[j]
function getPairs(A, B, n)
{
// Initializing the difference array D
let D = new Array(n);
// Computing the difference between the
// elements at every index and storing
// it in the array D
for (let i = 0; i < n; i++) {
D[i] = A[i] - B[i];
}
// Sort the array D
D.sort((a, b) => a - b);
// Variable to store the total
// number of pairs that satisfy
// the given condition
let total = 0;
// Loop to iterate through the difference
// array D and find the total number
// of pairs of indices that follow the
// given condition
for (int i = 0; i < n; ++i) {
// If the value at that index is negative or zero
// then we need to find the index of the
// value just greater than -D[i]
if (D[i] <= 0) {
int k = upper_bound(D,0,D.length, -D[i]);
total += n - k;
}
// If the value at the index is positive
//then we need to find the number of indexes after i-th index
else {
total += n-i-1;
}
}
return total;
}
function upper_bound(a, low, high, element)
{
while(low < high){
let middle = low + Math.floor((high - low)/2);
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver code
let n = 5;
let A = new Array();
let B = new Array();
A.push(4);
A.push(8);
A.push(2);
A.push(6);
A.push(2);
B.push(4);
B.push(5);
B.push(4);
B.push(1);
B.push(3);
document.write(getPairs(A, B, n))
</script>
// This code is contributed by Udit Mehta
Time Complexity Analysis:
- The sorting of the array takes O(N * log(N)) time.
- The time taken to find the index which is just greater than a specific value is O(Log(N)). Since in the worst case, this can be executed for N elements in the array, the overall time complexity for this is O(N * log(N)).
- Therefore, the overall time complexity is O(N * log(N)).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem