Number of Good Pairs - Count of index pairs with equal values in an array

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = [5, 2, 3, 5, 5, 3]
Output: 4
Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5)

Input: arr = [1, 1, 1, 1]
Output: 6
Explanation: All 6 pairs of indexes are good

Input: arr = [1, 2, 3]
Output: 0
Explanation: There are no good pairs since no elements are the same.

Naive Approach - O(n^2) Time and O(1) Space

For each index i, find element after it with same value as arr[i]. Below is the implementation of this approach: 

C++
#include <bits/stdc++.h>
using namespace std;

// Return the number of pairs with equal values.
int countPairs(const vector<int>& arr) {
    int count = 0;
    int n = arr.size();

    // 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]) {
                ++count;
            }
        }
    }
    return count;
}

// Driver Program
int main() {
    vector<int> arr = {1, 1, 2};
    cout << countPairs(arr) << 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 count = 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])
                    count++;
        return count;
    }
    
    //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.
Python
# Python3 program to
# count of pairs with equal
# elements in an array.

# Return the number of
# pairs with equal values.
def countPairs(arr, n):

    count = 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]):
                count += 1
    return count

# 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 count = 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])
                    count++;
        return count;
    }
    
    // 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.
JavaScript
const countPairs = (arr) => {
    let count = 0;
    const n = arr.length;

    // for each index i and j
    for (let i = 0; i < n; ++i) {
        for (let j = i + 1; j < n; ++j) {
        
            // finding the index with same value
            // but different index.
            if (arr[i] === arr[j]) {
                count++;
            }
        }
    }
    return count;
};

// Driver Program
const arr = [1, 1, 2];
console.log(countPairs(arr));
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)
Auxiliary Space: O(1)

Efficient Approach - O(n) Time and O(1) Space

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++
#include <bits/stdc++.h>
using namespace std;

// Return the number of pairs with equal values.
int countPairs(const vector<int>& arr) {
    unordered_map<int, int> mp;

    // Finding frequency of each number.
    int count = 0;
    for (int num : arr) {
      
        // Add current frequency and then
        // increment. Whenever we find a 
        // repition, all the previous seen
        // values will form a pair with it
        count = count + mp[num];
        mp[num]++;
    }  

    return count;
}

// Driver Program
int main() {
    vector<int> arr = {1, 1, 2};
    cout << countPairs(arr) << endl;
    return 0;
}
Java
import java.util.HashMap;

public class GfG {

    // Return the number of pairs with equal values.
    public static int countPairs(int[] arr) {
        HashMap<Integer, Integer> mp = new HashMap<>();

        int count = 0;
        for (int num : arr) {
          
            // Add current frequency and then increment.
            // Every repetition forms pairs with all previously seen values.
            count += mp.getOrDefault(num, 0);  
            mp.put(num, mp.getOrDefault(num, 0) + 1);  
        }

        return count;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2};
        System.out.println(countPairs(arr));  
    }
}
Python
from collections import defaultdict

def count_pairs(arr):
    mp = defaultdict(int)
    
    count = 0
    for num in arr:
      
        # Add current frequency and then increment.
        # Every repetition forms pairs with all 
        # previously seen values.
        count += mp[num]
        mp[num] += 1 
    
    return count

# Driver Program
arr = [1, 1, 2]
print(count_pairs(arr))  
C#
using System;
using System.Collections.Generic;

public class GfG {

    // Return the number of pairs with equal values.
    public static int CountPairs(int[] arr) {
        Dictionary<int, int> mp = new Dictionary<int, int>();

        int count = 0;
        foreach (int num in arr) {
          
            // Add current frequency and then increment.
            // Every repetition forms pairs with all previously seen values.
            if (mp.ContainsKey(num)) {
                count += mp[num];
                mp[num]++;
            } else {
                mp[num] = 1;
            }
        }

        return count;
    }

    // Driver Program
    public static void Main() {
        int[] arr = { 1, 1, 2 };
        Console.WriteLine(CountPairs(arr)); 
    }
}
JavaScript
function countPairs(arr) {
    let mp = {};
    let count = 0;

    arr.forEach(num => {
    
        // Add current frequency and then increment.
        // Every repetition forms pairs with all previously seen values.
        if (mp[num] !== undefined) {
            count += mp[num];
            mp[num]++;
        } else {
            mp[num] = 1;
        }
    });

    return count;
}

// Driver Program
const arr = [1, 1, 2];
console.log(countPairs(arr));  // Output: 1

Output
1

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

 


Next Article
Article Tags :
Practice Tags :

Similar Reads