Count pairs of equal elements possible by excluding each array element once
Last Updated :
22 Mar, 2023
Given an array arr[] of N integers, the task for each array element is to find the number of ways of choosing a pair of two equal elements excluding the current element.
Examples:
Input: arr[] = {1, 1, 2, 1, 2}
Output: 2 2 3 2 3
Explanation:
For arr[0] (= 1): The remaining array elements are {1, 2, 1, 2}. Possible choice of pairs are (1, 1), (2, 2). Therefore, count is 2.
For arr[1] (= 1): The remaining array elements are {1, 2, 1, 2}. Therefore, count is 2.
For arr[2] (= 2): The remaining array elements are {1, 1, 1, 2}. Possible choice of pairs are (arr[0], arr[1]), (arr[1], arr[2]) and (arr[0], arr[2]). Therefore, count is 3.
For arr[3] (= 1): The remaining elements are {1, 1, 2, 2}. Therefore, count is 2.
For arr[4] (= 2): The remaining elements are {1, 1, 2, 1}. Therefore, count is 3.
Input: arr[] = {1, 2, 1, 4, 2, 1, 4, 1}
Output: 5 7 5 7 7 5 7 5
Naive Approach: The simplest approach to solve this problem is to traverse the array for each array element, count all possible pairs of equal elements from the remaining array.
Implementation:-
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of
// required pairs for every array element
void countEqualElementPairs(int arr[], int N)
{
//Taking this loop to not consider element at index i
for(int i=0;i<N;i++)
{
//count for excluding arr[i]
int count=0;
//Counting all pairs except arr[i]
for(int j=0;j<N-1;j++)
{
if(j==i)continue;
for(int k=j+1;k<N;k++)
{
//k point to i which we don't have to consider
if(k==i) continue;
if(arr[k]==arr[j])count++;
}
}
cout<<count<<" ";
}
}
// Driver code
int main()
{
// Given array
int arr[] = { 1, 1, 2, 1, 2 };
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
countEqualElementPairs(arr, N);
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void countEqualElementPairs(int arr[], int N)
{
//Taking this loop to not consider element at index i
for(int i=0;i<N;i++)
{
//count for excluding arr[i]
int count=0;
//Counting all pairs except arr[i]
for(int j=0;j<N-1;j++)
{
if(j==i)continue;
for(int k=j+1;k<N;k++)
{
//k point to i which we don't have to consider
if(k==i) continue;
if(arr[k]==arr[j])count++;
}
}
System.out.print(count+" ");
}
}
public static void main (String[] args) {
//size of array
int N = 5;
//array
int arr[]={1,1,2,1,2};
//calling function
countEqualElementPairs(arr,N);
}
}
//this code is contributed by shubhamrajput6156
Python3
# Function to count the number of required pairs for every array element
def countEqualElementPairs(arr, N):
# Taking this loop to not consider element at index i
for i in range(N):
# count for excluding arr[i]
count = 0
# Counting all pairs except arr[i]
for j in range(N-1):
if j == i:
continue
for k in range(j+1, N):
# k point to i which we don't have to consider
if k == i:
continue
if arr[k] == arr[j]:
count += 1
print(count, end=" ")
# Driver code
if __name__ == '__main__':
# Given array
arr = [1, 1, 2, 1, 2]
# Size of the array
N = len(arr)
countEqualElementPairs(arr, N)
JavaScript
// Function to count the number of
// required pairs for every array element
function countEqualElementPairs(arr) {
const N = arr.length;
//Taking this loop to not consider element at index i
for (let i = 0; i < N; i++) {
//count for excluding arr[i]
let count = 0;
//Counting all pairs except arr[i]
for (let j = 0; j < N - 1; j++) {
if (j === i) continue;
for (let k = j + 1; k < N; k++) {
//k point to i which we don't have to consider
if (k === i) continue;
if (arr[k] === arr[j]) count++;
}
}
console.log(count);
}
}
// Driver code
const arr = [1, 1, 2, 1, 2];
countEqualElementPairs(arr);
C#
// C# program
using System;
class GFG {
static void countEqualElementPairs(int[] arr, int N)
{
// Taking this loop to not consider element at index
// i
for (int i = 0; i < N; i++) {
// count for excluding arr[i]
int count = 0;
// Counting all pairs except arr[i]
for (int j = 0; j < N - 1; j++) {
if (j == i)
continue;
for (int k = j + 1; k < N; k++) {
// k point to i which we don't have to
// consider
if (k == i)
continue;
if (arr[k] == arr[j])
count++;
}
}
Console.Write(count + " ");
}
}
// Driver code
public static void Main()
{
// Given array
int[] arr = { 1, 1, 2, 1, 2 };
// Size of the array
int N = arr.Length;
countEqualElementPairs(arr, N);
}
}
Time Complexity: O(N3)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the observation that, for any ith index (1 ≤ i ≤ N), calculate the following two values:
- The number of ways to choose two distinct elements having equal values from the array.
- The number of ways to choose an element from the N − 1 array elements other than the ith element such that their values are the same as the value of the ith element.
Follow the steps below to solve the problem:
- Initialize a map, say mp, to store the frequency of every array element.
- Traverse the map to count the number of pairs made up of equal values. Store the count in a variable, say total.
- Traverse the array and for every ith index, print total - (mp[arr[i]] - 1) as the required answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the number of
// required pairs for every array element
void countEqualElementPairs(int arr[], int N)
{
// Initialize a map
unordered_map<int, int> mp;
// Update the frequency
// of every element
for (int i = 0; i < N; i++) {
mp[arr[i]] += 1;
}
// Stores the count of pairs
int total = 0;
// Traverse the map
for (auto i : mp) {
// Count the number of ways to
// select pairs consisting of
// equal elements only
total += (i.second * (i.second - 1)) / 2;
}
// Traverse the array
for (int i = 0; i < N; i++) {
// Print the count for
// every array element
cout << total - (mp[arr[i]] - 1)
<< " ";
}
}
// Driver code
int main()
{
// Given array
int arr[] = { 1, 1, 2, 1, 2 };
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
countEqualElementPairs(arr, N);
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Map;
import java.util.HashMap;
class GFG
{
// Function to count the number of
// required pairs for every array element
public static void countEqualElementPairs(int arr[],
int N)
{
// Initialize a map
HashMap<Integer, Integer> map = new HashMap<>();
// Update the frequency
// of every element
for (int i = 0; i < N; i++)
{
Integer k = map.get(arr[i]);
map.put(arr[i], (k == null) ? 1 : k + 1);
}
// Stores the count of pairs
int total = 0;
// Traverse the map
for (Map.Entry<Integer, Integer> e :
map.entrySet())
{
// Count the number of ways to
// select pairs consisting of
// equal elements only
total
+= (e.getValue() * (e.getValue() - 1)) / 2;
}
// Traverse the array
for (int i = 0; i < N; i++) {
// Print the count for
// every array element
System.out.print(total - (map.get(arr[i]) - 1)
+ " ");
}
}
// Driver code
public static void main(String[] args)
{
// Given array
int arr[] = { 1, 1, 2, 1, 2 };
// Size of the array
int N = 5;
countEqualElementPairs(arr, N);
}
}
// This code is contributed by adity7409.
Python3
# Python3 program for the above approach
# Function to count the number of
# required pairs for every array element
def countEqualElementPairs(arr, N):
# Initialize a map
mp = {}
# Update the frequency
# of every element
for i in range(N):
if arr[i] in mp:
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
# Stores the count of pairs
total = 0
# Traverse the map
for key,value in mp.items():
# Count the number of ways to
# select pairs consisting of
# equal elements only
total += (value * (value - 1)) / 2
# Traverse the array
for i in range(N):
# Print the count for
# every array element
print(int(total - (mp[arr[i]] - 1)),end = " ")
# Driver code
if __name__ == '__main__':
# Given array
arr = [1, 1, 2, 1, 2]
# Size of the array
N = len(arr)
countEqualElementPairs(arr, N)
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to count the number of
// required pairs for every array element
static void countEqualElementPairs(int[] arr, int N)
{
// Initialize a map
Dictionary<int,
int> map = new Dictionary<int,
int>();
// Update the frequency
// of every element
for(int i = 0; i < N; i++)
{
if (!map.ContainsKey(arr[i]))
map[arr[i]] = 1;
else
map[arr[i]]++;
}
// Stores the count of pairs
int total = 0;
// Traverse the map
foreach(KeyValuePair<int, int> e in map)
{
// Count the number of ways to
// select pairs consisting of
// equal elements only
total += (e.Value * (e.Value - 1)) / 2;
}
// Traverse the array
for(int i = 0; i < N; i++)
{
// Print the count for
// every array element
Console.Write(total - (map[arr[i]] - 1) + " ");
}
}
// Driver code
public static void Main()
{
// Given array
int[] arr = { 1, 1, 2, 1, 2 };
// Size of the array
int N = 5;
countEqualElementPairs(arr, N);
}
}
// This code is contributed by ukasp
JavaScript
<script>
// Javascript program for the above approach
// Function to count the number of
// required pairs for every array element
function countEqualElementPairs(arr, N)
{
// Initialize a map
var mp = new Map();
// Update the frequency
// of every element
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);
}
}
// Stores the count of pairs
var total = 0;
// Traverse the map
mp.forEach((value, key) => {
// Count the number of ways to
// select pairs consisting of
// equal elements only
total += (value * (value - 1)) / 2;
});
// Traverse the array
for(var i = 0; i < N; i++)
{
// Print the count for
// every array element
document.write(total -
(mp.get(arr[i]) - 1) + " ");
}
}
// Driver code
// Given array
var arr = [ 1, 1, 2, 1, 2 ];
// Size of the array
var N = arr.length;
countEqualElementPairs(arr, N);
// This code is contributed by rutvik_56
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less t
13 min read
Count of pairs having each element equal to index of the other from an Array
Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i]. Examples: Input: N = 4, arr[] = {2, 1, 4, 3} Output: 2 Explanation: All possible pairs are {1, 2} and {3,
6 min read
Count of smaller or equal elements in sorted array
Given a sorted array of size n. Find a number of elements that are less than or equal to a given element. Examples: Input : arr[] = {1, 2, 4, 5, 8, 10} key = 9 Output : 5 Elements less than or equal to 9 are 1, 2, 4, 5, 8 therefore result will be 5. Input : arr[] = {1, 2, 2, 2, 5, 7, 9} key = 2 Outp
15+ min read
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 3Explanation:For index 1, remaining elements after excludi
7 min read
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements
Given an array arr[] of size N, the task is to make all array elements equal to 0 by replacing all elements of a subsequences of equal elements by any integer, minimum number of times. Examples: Input: arr[] = {3, 7, 3}, N = 3Output: 2Explanation:Selecting a subsequence { 7 } and replacing all its e
5 min read
Count of index pairs with equal elements in an array | Set 2
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
8 min read
Count pairs formed by distinct element sub-arrays
Given an array, count number of pairs that can be formed from all possible contiguous sub-arrays containing distinct numbers. The array contains positive numbers between 0 to n-1 where n is the size of the array. Examples: Input: [1, 4, 2, 4, 3, 2] Output: 8 The subarrays with distinct elements are
7 min read
Check if Array Elemnts can be Made Equal with Given Operations
Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
6 min read
Total count of elements having frequency one in each Subarray
Given an array arr[] of length N, the task is to find the total number of elements that has frequency 1 in a subarray of the given array. Examples: Input: N = 3, arr[ ] = {2, 4, 2}Output: 8Explanation: All possible subarrays are {2}: elements with frequency one = 1.{4}: elements with frequency one =
13 min read
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}.
11 min read