Related Articles

# Count pairs (i, j) from arrays arr[] & brr[] such that arr[i] – brr[j] = arr[j] – brr[i]

• Last Updated : 19 May, 2021

Given two arrays arr[] and brr[] consisting of N integers, the task is to count the number of pairs (i, j) from both the array such that (arr[i] – brr[j]) and (arr[j] – brr[i]) are equal.

Examples:

Input: A[] = {1, 2, 3, 2, 1}, B[] = {1, 2, 3, 2, 1}
Output:
Explanation: The pairs satisfying the condition are:

1. (1, 5): arr – brr = 1 – 1 = 0, arr[5[ – brr = 1 – 1 = 0
2. (2, 4): arr – brr = 2 – 2 = 0, arr – brr = 2 – 2 = 0

Input: A[] = {1, 4, 20, 3, 10, 5}, B[] = {9, 6, 1, 7, 11, 6}
Output:

Naive Approach: The simplest approach to solve the problem is to generate all pairs from two given arrays and check for the required condition. For every pair for which the condition is found to be true, increase count of such pairs. Finally, print the count obtained.

Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: The idea is to transform the given expression (a[i] – b[j] = a[j] – b[i]) into the form (a[i] + b[i] = a[j] + b[j]) and then calculate pairs satisfying the condition. Below are the steps:

1. Transform the expression, a[i] – b[j] = a[j] – b[i] ==> a[i] + b[i] = a[j] +b[j]. The general form of expression becomes to count the sum of values at each corresponding index of the two arrays for any pair (i, j).
2. Initialize an auxiliary array c[] to store the corresponding sum c[i] = a[i] + b[i] at each index i.
3. Now the problem reduces to find the number of possible pairs having same c[i] value.
4. Count the frequency of each element in the array c[] and If any c[i] frequency value is greater than one then it can make a pair.
5. Count the number of valid pairs in the above steps using formula: Below is the implementation of the above approach:

## C++

 // C++ program for the above approach #include using namespace std; // Function to count the pairs such that// given condition is satisfiedint CountPairs(int* a, int* b, int n){    // Stores the sum of element at    // each corresponding index    int C[n];     // Find the sum of each index    // of both array    for (int i = 0; i < n; i++) {        C[i] = a[i] + b[i];    }     // Stores frequency of each element    // present in sumArr    map<int, int> freqCount;     for (int i = 0; i < n; i++) {        freqCount[C[i]]++;    }     // Initialize number of pairs    int NoOfPairs = 0;     for (auto x : freqCount) {        int y = x.second;         // Add possible vaid pairs        NoOfPairs = NoOfPairs                    + y * (y - 1) / 2;    }     // Return Number of Pairs    cout << NoOfPairs;} // Driver Codeint main(){    // Given array arr[] and brr[]    int arr[] = { 1, 4, 20, 3, 10, 5 };     int brr[] = { 9, 6, 1, 7, 11, 6 };     // Size of given array    int N = sizeof(arr) / sizeof(arr);     // Function calling    CountPairs(arr, brr, N);     return 0;}

## Java

 // Java program for the above approachimport java.util.*;import java.io.*; class GFG{     // Function to find the minimum number// needed to be added so that the sum// of the digits does not exceed Kstatic void CountPairs(int a[], int b[], int n){         // Stores the sum of element at    // each corresponding index    int C[] = new int[n];       // Find the sum of each index    // of both array    for(int i = 0; i < n; i++)    {        C[i] = a[i] + b[i];    }         // Stores frequency of each element    // present in sumArr    // map freqCount;    HashMap freqCount = new HashMap<>();       for(int i = 0; i < n; i++)    {        if (!freqCount.containsKey(C[i]))            freqCount.put(C[i], 1);        else            freqCount.put(C[i],            freqCount.get(C[i]) + 1);    }       // Initialize number of pairs    int NoOfPairs = 0;       for(Map.Entry x : freqCount.entrySet())    {        int y = x.getValue();           // Add possible vaid pairs        NoOfPairs = NoOfPairs +                  y * (y - 1) / 2;    }       // Return Number of Pairs   System.out.println(NoOfPairs);} // Driver Codepublic static void main(String args[]){       // Given array arr[] and brr[]    int arr[] = { 1, 4, 20, 3, 10, 5 };    int brr[] = { 9, 6, 1, 7, 11, 6 };         // Size of given array    int N = arr.length;         // Function calling    CountPairs(arr, brr, N);}} // This code is contributed by bikram2001jha

## Python3

 # Python3 program for the above approach # Function to count the pairs such that# given condition is satisfieddef CountPairs(a, b, n):         # Stores the sum of element at    # each corresponding index    C =  * n      # Find the sum of each index    # of both array    for i in range(n):        C[i] = a[i] + b[i]         # Stores frequency of each element    # present in sumArr    freqCount = dict()      for i in range(n):        if C[i] in freqCount.keys():            freqCount[C[i]] += 1        else:            freqCount[C[i]] = 1      # Initialize number of pairs    NoOfPairs = 0      for x in freqCount:        y = freqCount[x]          # Add possible vaid pairs        NoOfPairs = (NoOfPairs + y *                       (y - 1) // 2)         # Return Number of Pairs    print(NoOfPairs) # Driver Code # Given array arr[] and brr[]arr = [ 1, 4, 20, 3, 10, 5 ]brr = [ 9, 6, 1, 7, 11, 6 ]  # Size of given arrayN = len(arr)  # Function callingCountPairs(arr, brr, N) # This code is contributed by code_hunt

## C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{     // Function to find the minimum number// needed to be added so that the sum// of the digits does not exceed Kstatic void CountPairs(int []a, int []b,                       int n){         // Stores the sum of element at    // each corresponding index    int []C = new int[n];       // Find the sum of each index    // of both array    for(int i = 0; i < n; i++)    {        C[i] = a[i] + b[i];    }         // Stores frequency of each element    // present in sumArr    // map freqCount;    Dictionary<int,               int> freqCount = new Dictionary<int,                                               int>();       for(int i = 0; i < n; i++)    {        if (!freqCount.ContainsKey(C[i]))            freqCount.Add(C[i], 1);        else            freqCount[C[i]] = freqCount[C[i]] + 1;    }       // Initialize number of pairs    int NoOfPairs = 0;       foreach(KeyValuePair<int,                         int> x in freqCount)    {        int y = x.Value;           // Add possible vaid pairs        NoOfPairs = NoOfPairs +                  y * (y - 1) / 2;    }         // Return Number of Pairs    Console.WriteLine(NoOfPairs);} // Driver Codepublic static void Main(String []args){         // Given array []arr and brr[]    int []arr = { 1, 4, 20, 3, 10, 5 };    int []brr = { 9, 6, 1, 7, 11, 6 };         // Size of given array    int N = arr.Length;         // Function calling    CountPairs(arr, brr, N);}} // This code is contributed by Amit Katiyar

## Javascript

 
Output:
4

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up