Count of index pairs with equal elements in an array | Set 2
Last Updated :
13 Jun, 2022
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: 4
Explanation:
In the array arr[0]=arr[1]=arr[3] and arr[2]=arr[4]
So Valid Pairs are (0, 1), (0, 3), (1, 3), (2, 4)
For the Naive and Efficient Approach please refer to the previous post of this article.
Better Approach - using Two Pointers: The idea is to sort the given array and the difference of index having the same elements. Below are the steps:
- Sort the given array.
- Initialize the two pointers left and right as 0 and 1 respectively.
- Now till right is less than N, do the following:
- If the element index left and right are the same then increment the right pointer and add the difference of right and left pointer to the final count.
- Else update the value of left to right.
- Print the value of count after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function that counts the pair in
// the array arr[]
int countPairs(int arr[], int n)
{
int ans = 0;
// Sort the array
sort(arr, arr + n);
// Initialize two pointers
int left = 0, right = 1;
while (right < n) {
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 2, 2, 3, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countPairs(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function that counts the pair in
// the array arr[]
static int countPairs(int arr[], int n)
{
int ans = 0;
// Sort the array
Arrays.sort(arr);
// Initialize two pointers
int left = 0, right = 1;
while (right < n)
{
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 2, 2, 3, 2, 3 };
int N = arr.length;
// Function call
System.out.print(countPairs(arr, N));
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program for the above approach
# Function that counts the pair in
# the array arr[]
def countPairs(arr, n):
ans = 0
# Sort the array
arr.sort()
# Initialize two pointers
left = 0
right = 1;
while (right < n):
if (arr[left] == arr[right]):
# Add all valid pairs to answer
ans += right - left;
else:
left = right;
right += 1
# Return the answer
return ans
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [2, 2, 3, 2, 3]
N = len(arr)
# Function call
print (countPairs(arr, N))
# This code is contributed by Chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// Function that counts the pair in
// the array []arr
static int countPairs(int []arr, int n)
{
int ans = 0;
// Sort the array
Array.Sort(arr);
// Initialize two pointers
int left = 0, right = 1;
while (right < n)
{
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 2, 2, 3, 2, 3 };
int N = arr.Length;
// Function call
Console.Write(countPairs(arr, N));
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript program for the above approach
// Function that counts the pair in
// the array arr[]
function countPairs(arr, n)
{
let ans = 0;
// Sort the array
arr.sort(function(a, b){return a - b});
// Initialize two pointers
let left = 0, right = 1;
while (right < n)
{
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Given array []arr
let arr = [ 2, 2, 3, 2, 3 ];
let N = arr.length;
// Function call
document.write(countPairs(arr, N));
</script>
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Efficient Approach - using single Traversal: The idea is to use Hashing and update the count of each pair whose frequency is greater than 1. Below are the steps:
- Create a unordered_map M to store the frequency of each element in the array.
- Traverse the given array and keep updating the frequency of each element in M.
- While updating frequency in the above step if the frequency of any element is greater than 0 then count that frequency to the final count.
- Print the count of pairs after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function that count the pairs having
// same elements in the array arr[]
int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurrences of elements
unordered_map<int, int> count;
// Traverse the array arr[]
for (int i = 0; i < n; i++) {
// Check if occurrence of arr[i] > 0
// add count[arr[i]] to answer
if (count[arr[i]] != 0)
ans += count[arr[i]];
// Increase count of arr[i]
count[arr[i]]++;
}
// Return the result
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countPairs(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function that count the pairs having
// same elements in the array arr[]
static int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurrences of elements
HashMap<Integer,
Integer> count = new HashMap<>();
// Traverse the array arr[]
for (int i = 0; i < n; i++)
{
// Check if occurrence of arr[i] > 0
// add count[arr[i]] to answer
if(count.containsKey(arr[i]))
{
ans += count.get(arr[i]);
count.put(arr[i], count.get(arr[i]) + 1);
}
else
{
count.put(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = arr.length;
// Function call
System.out.print(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program for the above approach
# Function that count the pairs having
# same elements in the array arr[]
def countPairs(arr, n) :
ans = 0
# Hash map to keep track of
# occurrences of elements
count = {}
# Traverse the array arr[]
for i in range(n) :
# Check if occurrence of arr[i] > 0
# add count[arr[i]] to answer
if arr[i] in count :
ans += count[arr[i]]
# Increase count of arr[i]
if arr[i] in count :
count[arr[i]] += 1
else :
count[arr[i]] = 1
# Return the result
return ans
# Given array arr[]
arr = [ 1, 2, 1, 1 ]
N = len(arr)
# Function call
print(countPairs(arr, N))
# This code is contributed by divyesh072019
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function that count the pairs having
// same elements in the array []arr
static int countPairs(int []arr, int n)
{
int ans = 0;
// Hash map to keep track of
// occurrences of elements
Dictionary<int,
int> count = new Dictionary<int,
int>();
// Traverse the array []arr
for (int i = 0; i < n; i++)
{
// Check if occurrence of arr[i] > 0
// add count[arr[i]] to answer
if(count.ContainsKey(arr[i]))
{
ans += count[arr[i]];
count[arr[i]] = count[arr[i]] + 1;
}
else
{
count.Add(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 1, 2, 1, 1 };
int N = arr.Length;
// Function call
Console.Write(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program for the above approach
// Function that count the pairs having
// same elements in the array arr[]
function countPairs(arr, n)
{
let ans = 0;
// Hash map to keep track of
// occurrences of elements
let count = new Map();
// Traverse the array arr[]
for(let i = 0; i < n; i++)
{
// Check if occurrence of arr[i] > 0
// add count[arr[i]] to answer
if (count.has(arr[i]))
{
ans += count.get(arr[i]);
count.set(arr[i], count.get(arr[i]) + 1);
}
else
{
count.set(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
let arr = [ 1, 2, 1, 1 ];
let N = arr.length;
// Function call
document.write(countPairs(arr, N));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
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 pairs in an array such that both elements has equal set bits Given an array arr [] of size N with unique elements, the task is to count the total number of pairs of elements that have equal set bits count. Examples: Input: arr[] = {2, 5, 8, 1, 3} Output: 4 Set bits counts for {2, 5, 8, 1, 3} are {1, 2, 1, 1, 2} All pairs with same set bits count are {2, 8}, {
6 min read
Partition an array into two subsets with equal count of unique elements Given an array arr[] consisting of N integers, the task is to partition the array into two subsets such that the count of unique elements in both the subsets is the same and for each element, print 1 if that element belongs to the first subset. Otherwise, print 2. If it is not possible to do such a
13 min read
Count pairs in an array having sum of elements with their respective sum of digits equal Given an array arr[] consisting of N positive integers, the task is to count the number of pairs in the array, say (a, b) such that sum of a with its sum of digits is equal to sum of b with its sum of digits. Examples: Input: arr[] = {1, 1, 2, 2}Output: 2Explanation:Following are the pairs that sati
8 min read
Number of Good Pairs - Count of index pairs with equal values in an array Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < jExamples : Input: arr = [5, 2, 3, 5, 5, 3]Output: 4Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5)Input: arr = [1, 1, 1, 1]Output: 6Explanation: All 6 pairs
6 min read
Find the count of even odd pairs in a given Array Given an array arr[], the task is to find the count even-odd pairs in the array.Examples: Input: arr[] = { 1, 2, 1, 3 } Output: 2 Explanation: The 2 pairs of the form (even, odd) are {2, 1} and {2, 3}. Input: arr[] = { 5, 4, 1, 2, 3} Output: 3 Naive Approach: Run two nested loops to get all the poss
7 min read
Count pairs of equal array elements remaining after every removal Given an array arr[] of size N, the task for every array element arr[i], is to count the number of pairs of equal elements that can be obtained by removing arr[i] from the array. Examples: Input: arr[] = { 1, 1, 1, 2 } Output: 1 1 1 3 Explanation: Removing arr[0] from the array modifies arr[] to { 1
11 min read
Count of all possible pairs of array elements with same parity Given an array A[] of integers, the task is to find the total number of pairs such that each pair contains either both even or both odd elements. A valid pair (A[ i ], A[ j ]) can only be formed if i != j. Examples: Input: A[ ] = {1, 2, 3, 1, 3} Output: 6 Explanation: Possible odd pairs = (1, 3), (1
7 min read
Count of pairs in an Array with same number of set bits Given an array arr containing N integers, the task is to count the possible number of pairs of elements with the same number of set bits. Examples: Input: N = 8, arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 9 Explanation: Elements with 1 set bit: 1, 2, 4, 8 Elements with 2 set bits: 3, 5, 6 Elements wit
7 min read
Count pairs in given Array having sum of index and value at that index equal Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0â¤i<jâ¤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: a
8 min read