GFG App
Open App
Browser
Continue

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

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[1] – brr[5] = 1 – 1 = 0, arr[5[ – brr[1] = 1 – 1 = 0
2. (2, 4): arr[2] – brr[4] = 2 – 2 = 0, arr[4] – brr[2] = 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 satisfied int 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 valid pairs         NoOfPairs = NoOfPairs                     + y * (y - 1) / 2;     }       // Return Number of Pairs     cout << NoOfPairs; }   // Driver Code int 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[0]);       // Function calling     CountPairs(arr, brr, N);       return 0; }

## Java

 // Java program for the above approach  import 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 K  static 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 valid pairs          NoOfPairs = NoOfPairs +                    y * (y - 1) / 2;      }          // Return Number of Pairs     System.out.println(NoOfPairs); }    // Driver Code  public 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 satisfied def CountPairs(a, b, n):           # Stores the sum of element at     # each corresponding index     C = [0] * 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 valid 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 array N = len(arr)    # Function calling CountPairs(arr, brr, N)   # This code is contributed by code_hunt

## C#

 // C# program for the above approach  using 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 K  static 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 valid pairs          NoOfPairs = NoOfPairs +                    y * (y - 1) / 2;      }            // Return Number of Pairs      Console.WriteLine(NoOfPairs); }    // Driver Code  public 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)

My Personal Notes arrow_drop_up