Open In App

Count pairs from an array having product of their sum and difference equal to 0

Given an array arr[] of size N, the task is to count possible pairs of array elements (arr[i], arr[j]) such that (arr[i] + arr[j]) * (arr[i] – arr[j]) is 0.

Examples:



Input: arr[] = {2, -2, 1, 1}
Output : 2
Explanation:
(arr[0] + arr[1]) * (arr[0] – arr[1]) = 0
(arr[3] + arr[4]) * (arr[3] – arr[4]) = 0

Input: arr[] = {5, 9, -9, -9}
Output : 3



Naive approach:

Generate all the pairs and for each pair check if the given condition holds true, for all such valid pair increment the count.

Below is the implementation of the above approach:




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to count required
// number of pairs
void countPairs(int arr[], int N)
{
    int count = 0;
  
    // Generate all the possible pair
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
  
            // Check if the given condition holds true
            if ((arr[i] + arr[j]) * (arr[i] - arr[j])
                == 0) {
                count++;
            }
        }
    }
  
    // Print the total count
    cout << count << endl;
}
  
// Driver Code
int main()
{
    // Given arr[]
    int arr[] = { 2, -2, 1, 1 };
  
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    countPairs(arr, N);
  
    return 0;
}




import java.io.*;
  
class GFG {
    // Function to count required
    // number of pairs
    public static void countPairs(int[] arr, int N)
    {
        int count = 0;
  
        // Generate all the possible pair
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
  
                // Check if the given condition holds true
                if ((arr[i] + arr[j]) * (arr[i] - arr[j])
                    == 0) {
                    count++;
                }
            }
        }
  
        // Print the total count
        System.out.println(count);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        // Given arr[]
        int[] arr = { 2, -2, 1, 1 };
  
        // Size of the array
        int N = arr.length;
  
        // Function Call
        countPairs(arr, N);
    }
}




def countPairs(arr, N):
    count = 0
    for i in range(N):
        for j in range(i+1, N):
            if (arr[i] + arr[j]) * (arr[i] - arr[j]) == 0:
                count += 1
    print(count)
  
arr = [2, -2, 1, 1]
N = len(arr)
countPairs(arr, N)




using System;
  
public class Gfg {
    static void Main(string[] args)
    {
        // Given arr[]
        int[] arr = { 2, -2, 1, 1 };
  
        // Size of the array
        int N = arr.Length;
  
        // Function Call
        countPairs(arr, N);
    }
  
    // Function to count required
    // number of pairs
    static void countPairs(int[] arr, int N)
    {
        int count = 0;
  
        // Generate all the possible pair
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                // Check if the given condition holds true
                if ((arr[i] + arr[j]) * (arr[i] - arr[j])
                    == 0) {
                    count++;
                }
            }
        }
  
        // Print the total count
        Console.WriteLine(count);
    }
}




// Javascript program for the above approach
  
// Function to count required
// number of pairs
function countPairs(arr, N)
{
    let count = 0;
  
    // Generate all the possible pair
    for (let i = 0; i < N; i++) {
        for (let j = i + 1; j < N; j++) {
  
            // Check if the given condition holds true
            if ((arr[i] + arr[j]) * (arr[i] - arr[j])
                == 0) {
                count++;
            }
        }
    }
  
    // Print the total count
    document.write(count);
}
  
// Driver Code
    // Given arr[]
    let arr = [2, -2, 1, 1 ];
  
    // Size of the array
    let N = arr.length;
  
    // Function Call
    countPairs(arr, N);

Output
2

Time Complexity: O(n*n)
Auxiliary Space: O(1)

Approach: It can be observed that the equation (arr[i] + arr[j]) * (arr[i] – arr[j]) = 0 can be reduced to arr[i]2 = arr[j]2. Therefore, the task reduces to counting pairs having absolute value equal. Follow the steps below to solve the problem:  

Below is the implementation of the above approach:




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
#define MAXN 100005
  
// Function to count required
// number of pairs
int countPairs(int arr[], int N)
{
    // Stores count of pairs
    int desiredPairs = 0;
  
    // Initialize hash with 0
    int hash[MAXN] = { 0 };
  
    // Count frequency of each element
    for (int i = 0; i < N; i++) {
        hash[abs(arr[i])]++;
    }
  
    // Calculate desired number of pairs
    for (int i = 0; i < MAXN; i++) {
        desiredPairs
            += ((hash[i]) * (hash[i] - 1)) / 2;
    }
  
    // Print desired pairs
    cout << desiredPairs;
}
  
// Driver Code
int main()
{
    // Given arr[]
    int arr[] = { 2, -2, 1, 1 };
  
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    countPairs(arr, N);
  
    return 0;
}




// Java program for the above approach
import java.io.*;
import java.util.Arrays; 
  
class GFG{
    
static int MAXN = 100005;
  
// Function to count required
// number of pairs
static void countPairs(int arr[], int N)
{
      
    // Stores count of pairs
    int desiredPairs = 0;
  
    // Initialize hash with 0
    int hash[] = new int[MAXN];
    Arrays.fill(hash, 0);
  
    // Count frequency of each element
    for(int i = 0; i < N; i++) 
    {
        hash[(Math.abs(arr[i]))]++;
    }
  
    // Calculate desired number of pairs
    for(int i = 0; i < MAXN; i++)
    {
        desiredPairs += ((hash[i]) * 
                         (hash[i] - 1)) / 2;
    }
  
    // Print desired pairs
    System.out.print(desiredPairs);
}   
    
// Driver Code
public static void main (String[] args) 
{
      
    // Given arr[]
    int arr[] = { 2, -2, 1, 1 };
  
    // Size of the array
    int N = arr.length;
  
    // Function call
    countPairs(arr, N);
}
}
  
// This code is contributed by code_hunt




# Python3 program for 
# the above approach
MAXN = 100005
  
# Function to count required
# number of pairs
def countPairs(arr, N):
  
    # Stores count of pairs
    desiredPairs = 0
  
    # Initialize hash with 0
    hash = [0] * MAXN
  
    # Count frequency of 
    # each element
    for i in range(N):
        hash[abs(arr[i])] += 1
     
    # Calculate desired number 
    # of pairs
    for i in range(MAXN):
        desiredPairs += ((hash[i]) * 
                         (hash[i] - 1)) // 2
      
    # Print desired pairs
    print (desiredPairs)
  
# Driver Code
if __name__ == "__main__":
    
    # Given arr[]
    arr = [2, -2, 1, 1]
  
    # Size of the array
    N = len(arr)
  
    # Function Call
    countPairs(arr, N)
  
# This code is contributed by Chitranayal




// C# program for the above approach
using System;
  
class GFG{
    
static int MAXN = 100005;
  
// Function to count required
// number of pairs
static void countPairs(int []arr, int N)
{
      
    // Stores count of pairs
    int desiredPairs = 0;
  
    // Initialize hash with 0
    int []hash = new int[MAXN];
  
    // Count frequency of each element
    for(int i = 0; i < N; i++) 
    {
        hash[(Math.Abs(arr[i]))]++;
    }
  
    // Calculate desired number of pairs
    for(int i = 0; i < MAXN; i++)
    {
        desiredPairs += ((hash[i]) * 
                         (hash[i] - 1)) / 2;
    }
  
    // Print desired pairs
    Console.Write(desiredPairs);
}   
    
// Driver Code
public static void Main(String[] args) 
{
      
    // Given []arr
    int []arr = { 2, -2, 1, 1 };
  
    // Size of the array
    int N = arr.Length;
  
    // Function call
    countPairs(arr, N);
}
}
  
// This code is contributed by Amit Katiyar




<script>
  
// Javascript program for the above approach
  
// Function to count required
// number of pairs
function countPairs(arr, N)
{
    // Stores count of pairs
    let desiredPairs = 0;
  
    // Initialize hash with 0
    let hash = new Uint8Array(9100005);
  
    // Count frequency of each element
    for (let i = 0; i < N; i++) {
        hash[(Math.abs(arr[i]))]++;
    }
  
    // Calculate desired number of pairs
    for (let i = 0; i < 9100005; i++) {
        desiredPairs
            += ((hash[i]) * (hash[i] - 1)) / 2;
    }
  
    // Print desired pairs
    document.write(desiredPairs);
}
  
// Driver Code
  
    // Given arr[]
    let arr = [2, -2, 1, 1];
  
    // Size of the array
    let N = arr.length;
  
    // Function Call
    countPairs(arr, N);
  
// This code is contributed by Mayank Tyagi
  
</script>

Output
2

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


Article Tags :