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:

\frac{c[i]*(c[i] - 1)}{2}

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
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 vaid 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<int, int> freqCount;
    HashMap<Integer,
            Integer> 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<Integer,
                  Integer> 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 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 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 array
N = len(arr)
  
# Function calling
CountPairs(arr, brr, N)
 
# This code is contributed by code_hunt

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<int, int> 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 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

chevron_right


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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.