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 != j
Examples :
Input : arr[] = {1, 1, 2}
Output : 1
As arr[0] = arr[1], the pair of indices is (0, 1)
Input : arr[] = {1, 1, 1}
Output : 3
As arr[0] = arr[1], the pair of indices is (0, 1),
(0, 2) and (1, 2)
Input : arr[] = {1, 2, 3}
Output : 0
Method 1 (Brute Force):
For each index i, find element after it with same value as arr[i]. Below is the implementation of this approach:
C++
// C++ program to count of pairs with equal // elements in an array. #include<bits/stdc++.h> using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driven Program int main() { int arr[] = { 1, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; } |
Java
// Java program to count of pairs with equal // elements in an array. class GFG { // Return the number of pairs with equal // values. static int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } //driver code public static void main (String[] args) { int arr[] = { 1, 1, 2 }; int n = arr.length; System.out.println(countPairs(arr, n)); } } // This code is contributed by Anant Agarwal. |
Python3
# Python3 program to # count of pairs with equal # elements in an array. # Return the number of # pairs with equal values. def countPairs(arr, n): ans = 0 # for each index i and j for i in range(0 , n): for j in range(i + 1, n): # finding the index # with same value but # different index. if (arr[i] == arr[j]): ans += 1 return ans # Driven Code arr = [1, 1, 2 ] n = len(arr) print(countPairs(arr, n)) # This code is contributed # by Smitha |
C#
// C# program to count of pairs with equal // elements in an array. using System; class GFG { // Return the number of pairs with equal // values. static int countPairs(int []arr, int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driver code public static void Main () { int []arr = { 1, 1, 2 }; int n = arr.Length; Console.WriteLine(countPairs(arr, n)); } } // This code is contributed by anuj_67. |
PHP
<?php // PHP program to count of // pairs with equal elements // in an array. // Return the number of pairs // with equal values. function countPairs( $arr, $n) { $ans = 0; // for each index i and j for ( $i = 0; $i < $n; $i++) for ( $j = $i + 1; $j < $n; $j++) // finding the index with same // value but different index. if ($arr[$i] == $arr[$j]) $ans++; return $ans; } // Driven Code $arr = array( 1, 1, 2 ); $n = count($arr); echo countPairs($arr, $n) ; // This code is contributed by anuj_67. ?> |
Output :
1
Time Complexity : O(n2)
Method 2 (Efficient approach):
The idea is to count the frequency of each number and then find the number of pairs with equal elements. Suppose, a number x appears k times at index i1, i2,….,ik. Then pick any two indexes ix and iy which will be counted as 1 pair. Similarly, iy and ix can also be pair. So, choose nC2 is the number of pairs such that arr[i] = arr[j] = x.
Below is the implementation of this approach:
C++
// C++ program to count of index pairs with // equal elements in an array. #include<bits/stdc++.h> using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { unordered_map<int, int> mp; // Finding frequency of each number. for (int i = 0; i < n; i++) mp[arr[i]]++; // Calculating pairs of each value. int ans = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int count = it->second; ans += (count * (count - 1))/2; } return ans; } // Driven Program int main() { int arr[] = {1, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; } |
Java
// Java program to count of index pairs with // equal elements in an array. import java.util.*; class GFG { public static int countPairs(int arr[], int n) { //A method to return number of pairs with // equal values HashMap<Integer,Integer> hm = new HashMap<>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.containsKey(arr[i])) hm.put(arr[i],hm.get(arr[i]) + 1); else hm.put(arr[i], 1); } int ans=0; // Calculating count of pairs with equal values for(Map.Entry<Integer,Integer> it : hm.entrySet()) { int count = it.getValue(); ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void main(String[] args) { int arr[] = new int[]{1, 2, 3, 1}; System.out.println(countPairs(arr,arr.length)); } } // This Code is Contributed // by Adarsh_Verma |
Python3
# Python3 program to count of index pairs # with equal elements in an array. import math as mt # Return the number of pairs with # equal values. def countPairs(arr, n): mp = dict() # Finding frequency of each number. for i in range(n): if arr[i] in mp.keys(): mp[arr[i]] += 1 else: mp[arr[i]] = 1 # Calculating pairs of each value. ans = 0 for it in mp: count = mp[it] ans += (count * (count - 1)) // 2 return ans # Driver Code arr = [1, 1, 2] n = len(arr) print(countPairs(arr, n)) # This code is contributed by mohit kumar 29 |
C#
// C# program to count of index pairs with // equal elements in an array. using System; using System.Collections.Generic; class GFG { // Return the number of pairs with // equal values. public static int countPairs(int []arr, int n) { // A method to return number of pairs // with equal values Dictionary<int, int> hm = new Dictionary<int, int>(); // Finding frequency of each number. for(int i = 0; i < n; i++) { if(hm.ContainsKey(arr[i])) { int a = hm[arr[i]]; hm.Remove(arr[i]); hm.Add(arr[i], a + 1); } else hm.Add(arr[i], 1); } int ans = 0; // Calculating count of pairs with // equal values foreach(var it in hm) { int count = it.Value; ans += (count * (count - 1)) / 2; } return ans; } // Driver code public static void Main() { int []arr = new int[]{1, 2, 3, 1}; Console.WriteLine(countPairs(arr,arr.Length)); } } // This code is contributed by 29AjayKumar |
Output :
1
Time Complexity : O(n)
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimum index i such that all the elements from index i to given index are equal
- Count of index pairs with equal elements in an array | Set 2
- Count of pairs having each element equal to index of the other from an Array
- Check if every index i has an index j such that sum of elements in both directions are equal
- Number of permutations such that sum of elements at odd index and even index are equal
- Rearrange array such that even index elements are smaller and odd index elements are greater
- Queries for number of distinct elements from a given index till last index in an array
- Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements
- Count pairs in an array such that both elements has equal set bits
- Index of the elements which are equal to the sum of all succeeding elements
- Count of index pairs in array whose range product is a positive integer
- Count of contiguous subarrays possible for every index by including the element at that index
- Count of Array elements greater than or equal to twice the Median of K trailing Array elements
- Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
- Minimum increments by index value required to obtain at least two equal Array elements
- Split an Array A[] into Subsets having equal Sum and sizes equal to elements of Array B[]
- Sort Array such that smallest is at 0th index and next smallest it at last index and so on
- Farthest index that can be reached from the Kth index of given array by given operations
- Minimum elements to change so that for an index i all elements on the left are -ve and all elements on the right are +ve
- Count smaller elements on right side and greater elements on left side using Binary Index Tree

