Count all distinct pairs of repeating elements from the array for every array element
Last Updated :
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 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 int
using namespace std;
// Function to print the required
// count of pairs excluding the
// current element
void 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 Code
int32_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 approach
import java.util.*;
class GFG{
// Function to print the required
// count of pairs excluding the
// current element
static 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 Code
public 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 element
def 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 Code
if __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 approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the required
// count of pairs excluding the
// current element
static 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 Code
public 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 element
function 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 Call
solve(arr, N);
</script>
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read