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

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 3
Explanation:
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 0
Explanation:
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[].
Below is the implementation of the above approach:
C++
// 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
// 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
# 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#
// 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 |
Javascript
<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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



