Count all distinct pairs of repeating elements from the array for every array element - GeeksforGeeks

10 Nov, 2021
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j].
Examples:
Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count is 2.For index 2, remaining elements after excluding element at index 2 are [1, 2, 1, 2]. So the count is 2.For index 3, remaining elements after excluding element at index 3 are [1, 1, 1, 2]. So the count is 3.For index 4, remaining elements after excluding element at index 4 are [1, 1, 2, 2]. So the count is 2.For index 5, remaining elements after excluding element at index 5 are [1, 1, 2, 1. So the count is 3.
Input: arr[] = {1, 2, 3, 4}Output: 0 0 0 0Explanation:Since all the elements are distinct, so no pair with equal value exists.
Naive Approach: The naive idea is to traverse the given array and for each element exclude the current element from the array and with the remaining array elements find all the possible pairs (i, j) such that arr[i] is equal to arr[j] and i < j. Print the count of pairs for each element. Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: The idea is to store the frequency of every element and count all the possible pairs(say cnt) with the given conditions. After the above steps for each element remove the count of equal possible pairs from the total count cnt and print that value. Follow the below steps to solve the problem:
Store the frequency of each element in Map.Create a variable to store the contribution of each element.Contribution of some number x can be calculated as freq[x]*(freq[x] – 1) divided by 2, where freq[x] is the frequency of x.Traverse the given array and remove the contribution of each element from the total count and store it in ans[].Print all the elements stored in ans[].
Store the frequency of each element in Map.
Create a variable to store the contribution of each element.
Contribution of some number x can be calculated as freq[x]*(freq[x] – 1) divided by 2, where freq[x] is the frequency of x.
Traverse the given array and remove the contribution of each element from the total count and store it in ans[].
Print all the elements stored in ans[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for// the above approach#include <bits/stdc++.h>#define int long long intusing namespace std; // Function to print the required// count of pairs excluding the// current elementvoid solve(int arr[], int n){    // Store the frequency    unordered_map<int, int> mp;    for (int i = 0; i < n; i++) {        mp[arr[i]]++;    }     // Find all the count    int cnt = 0;    for (auto x : mp) {        cnt += ((x.second)                * (x.second - 1) / 2);    }     int ans[n];     // Delete the contribution of    // each element for equal pairs    for (int i = 0; i < n; i++) {         ans[i] = cnt - (mp[arr[i]] - 1);    }     // Print the answer    for (int i = 0; i < n; i++) {        cout << ans[i] << " ";    }} // Driver Codeint32_t main(){    // Given array arr[]    int arr[] = { 1, 1, 2, 1, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function Call    solve(arr, N);    return 0;}
// Java program for// the above approachimport java.util.*;class GFG{ // Function to print the required// count of pairs excluding the// current elementstatic void solve(int arr[],                  int n){  // Store the frequency  HashMap<Integer,          Integer> mp = new HashMap<Integer,                                    Integer>();  for (int i = 0; i < n; i++)  {    if(mp.containsKey(arr[i]))    {      mp.put(arr[i], mp.get(arr[i]) + 1);    }    else    {      mp.put(arr[i], 1);    }  }   // Find all the count  int cnt = 0;  for (Map.Entry<Integer,                 Integer> x : mp.entrySet())  {    cnt += ((x.getValue()) *            (x.getValue() - 1) / 2);  }   int []ans = new int[n];   // Delete the contribution of  // each element for equal pairs  for (int i = 0; i < n; i++)  {    ans[i] = cnt - (mp.get(arr[i]) - 1);  }   // Print the answer  for (int i = 0; i < n; i++)  {    System.out.print(ans[i] + " ");  }} // Driver Codepublic static void main(String[] args){  // Given array arr[]  int arr[] = {1, 1, 2, 1, 2};   int N = arr.length;   // Function Call  solve(arr, N);}} // This code is contributed by 29AjayKumar
# Python3 program for# the above approach # Function to print required# count of pairs excluding the# current elementdef solve(arr, n):         # Store the frequency    mp = {}    for i in arr:        mp[i] = mp.get(i, 0) + 1     # Find all the count    cnt = 0    for x in mp:        cnt += ((mp[x]) *                (mp[x] - 1) // 2)     ans = [0] * n     # Delete the contribution of    # each element for equal pairs    for i in range(n):        ans[i] = cnt - (mp[arr[i]] - 1)     # Print the answer    for i in ans:        print(i, end = " ") # Driver Codeif __name__ == '__main__':         # Given array arr[]    arr = [1, 1, 2, 1, 2]     N = len(arr)     # Function call    solve(arr, N)     # This code is contributed by mohit kumar 29
// C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to print the required// count of pairs excluding the// current elementstatic void solve(int []arr,                  int n){  // Store the frequency  Dictionary<int,             int> mp = new Dictionary<int,                                      int>();  for (int i = 0; i < n; i++)  {    if(mp.ContainsKey(arr[i]))    {      mp[arr[i]] =  mp[arr[i]] + 1;    }    else    {      mp.Add(arr[i], 1);    }  }   // Find all the count  int cnt = 0;  foreach (KeyValuePair<int,                        int> x in mp)  {    cnt += ((x.Value) *            (x.Value - 1) / 2);  }   int []ans = new int[n];   // Delete the contribution of  // each element for equal pairs  for (int i = 0; i < n; i++)  {    ans[i] = cnt - (mp[arr[i]] - 1);  }   // Print the answer  for (int i = 0; i < n; i++)  {    Console.Write(ans[i] + " ");  }} // Driver Codepublic static void Main(String[] args){  // Given array []arr  int []arr = {1, 1, 2, 1, 2};   int N = arr.Length;   // Function Call  solve(arr, N);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for// the above approach // Function to print the required// count of pairs excluding the// current elementfunction solve(arr, n){    // Store the frequency    var mp = new Map();    for (var i = 0; i < n; i++) {        if(mp.has(arr[i]))            mp.set(arr[i], mp.get(arr[i])+1)        else            mp.set(arr[i], 1);    }     // Find all the count    var cnt = 0;    mp.forEach((value, key) => {                 cnt += ((value)                * (value - 1) / 2);    });     var ans = Array(n);     // Delete the contribution of    // each element for equal pairs    for (var i = 0; i < n; i++) {         ans[i] = cnt - (mp.get(arr[i]) - 1);    }     // Print the answer    for (var i = 0; i < n; i++) {        document.write( ans[i] + " ");    }} // Driver Code// Given array arr[]var arr = [1, 1, 2, 1, 2];var N = arr.length;// Function Callsolve(arr, N); </script>
2 2 3 2 3
Time Complexity: O(NlogN)Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
itsok
khushboogoyal499
cpp-map
frequency-counting
Hash
Arrays
Hash
Mathematical
Arrays
Hash
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Find duplicates in O(n) time and O(1) extra space | Set 1
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)