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: 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:

  1. Sort the given array.
  2. Initialize the two pointers left and right as 0 and 1 respectively.
  3. 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.
  4. Print the value of count after the above steps.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Output: 

4







 

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:

  1. Create a unordered_map M to store the frequency of each element in the array.
  2. Traverse the given array and keep updating the frequency of each element in M.
  3. 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.
  4. Print the count of pairs after the above steps.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    // occurences of elements
    unordered_map<int, int> count;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Check if occurence 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    // occurences of elements
    HashMap<Integer,
            Integer> count = new HashMap<>();
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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
    // occurences of elements
    Dictionary<int,
                 int> count = new Dictionary<int,
                                             int>();
 
    // Traverse the array []arr
    for (int i = 0; i < n; i++)
    {
 
        // Check if occurence 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

chevron_right


Output: 

3







 

Time Complexity: O(N)
Auxiliary Space: O(N) 

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.