Count of unique pairs (arr[i], arr[j]) such that i < j

Given an array arr[], the task is to print the count of unique pairs (arr[i], arr[j]) such that i < j.

Examples:

Input: arr[] = {1, 2, 1, 4, 5, 2}
Output: 11
The possible pairs are (1, 2), (1, 1), (1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (2, 2), (4, 5), (4, 2), (5, 2)



Input: arr[] = {1, 2, 3, 4}
Output: 6
The possible pairs are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)

Naive approach: The easiest way is to iterate through every possible pair and if it satisfies the condition, then add it to a set. Then, we can return the size of the set as our answer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <iostream>
#include <set>
using namespace std;
   
// Function to return the count  
// of unique pairs in the array  
int getPairs(int arr[], int n)
{
    // Set to store unique pairs  
    set<pair<int, int>> h;
    for(int i = 0; i < (n - 1); i++)
    
        for (int j = i + 1; j < n; j++) 
        {
            // Create pair of (arr[i], arr[j])  
            // and add it to the hashset  
            h.insert(make_pair(arr[i], arr[j]));  
        }
    }
      
    // Return the size of the HashSet  
    return h.size(); 
}
      
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 };
    int  n = sizeof(arr) / sizeof(arr[0]);
    printf("%d", getPairs(arr, n)) ;
    return 0;
}
   
// This code is contributed by SHUBHAMSINGH10

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.HashSet;
import javafx.util.Pair;
  
class GFG {
  
    // Function to return the count
    // of unique pairs in the array
    static int getPairs(int arr[], int n)
    {
  
        // HashSet to store unique pairs
        HashSet<Pair> h = new HashSet<Pair>();
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
  
                // Create pair of (a[i], a[j])
                // and add it to the hashset
                Pair<Integer, Integer> p
                    = new Pair<>(arr[i], arr[j]);
                h.add(p);
            }
        }
  
        // Return the size of the HashSet
        return h.size();
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 };
        int n = arr.length;
        System.out.println(getPairs(arr, n));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
   
# Function to return the count 
# of unique pairs in the array 
def getPairs(arr, n) :
       
    # Set to store unique pairs 
    h = set() 
    for i in range(n - 1) :
        for j in range(i + 1, n) :
              
            # Create pair of (a[i], a[j]) 
            # and add it to the hashset 
            h.add((arr[i], arr[j])); 
               
    # Return the size of the HashSet 
    return len(h); 
   
# Driver code 
if __name__ == "__main__" :
        
    arr = [ 1, 2, 2, 4, 2, 5, 3, 5
    n = len(arr) 
       
    print(getPairs(arr, n))
       
# This code is contributed by Ryuga

chevron_right


Output:

14

Time Complexity: O(n2)
Note: Please use an offline IDE to compile the above code. Online compilers might not support JavaFX.

Efficient Approach: Every element arr[i] can form a pair with the element arr[j] if i < j. But (arr[i], arr[j]) should be unique therefore for every unique arr[i], possible pairs will be equal to the number of distinct numbers in the sub-array arr[i + 1], arr[i + 2], …, arr[n – 1]. So for every arr[i], we will find the unique elements from right to left. For this task, it is easy to keep track of the elements visited by using a Hash Tablle. In this way, we will have unique arr[i] for every unique arr[j]. Now, we will sum these values for every unique arr[i] which is the desired count of pairs.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.HashSet;
  
public class GFG {
  
    // Function to return the count
    // of unique pairs in the array
    static int getPairs(int a[], int n)
    {
        HashSet<Integer> visited1 = new HashSet<Integer>();
  
        // un[i] stores number of unique elements
        // from un[i + 1] to un[n - 1]
        int un[] = new int[n];
  
        // Last element will have no unique elements
        // after it
        un[n - 1] = 0;
  
        // To count unique elements after every a[i]
        int count = 0;
        for (int i = n - 1; i > 0; i--) {
  
            // If current element has already been used
            // i.e. not unique
            if (visited1.contains(a[i]))
                un[i - 1] = count;
            else
                un[i - 1] = ++count;
  
            // Set to true if a[i] is visited
            visited1.add(a[i]);
        }
  
        HashSet<Integer> visited2 = new HashSet<Integer>();
  
        // To know which a[i] is already visited
        int answer = 0;
        for (int i = 0; i < n - 1; i++) {
  
            // If visited, then the pair would
            // not be unique
            if (visited2.contains(a[i]))
                continue;
  
            // Calculating total unqiue pairs
            answer += un[i];
  
            // Set to true if a[i] is visited
            visited2.add(a[i]);
        }
        return answer;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 1, 2, 2, 4, 2, 5, 3, 5 };
        int n = a.length;
  
        // Print the count of unique pairs
        System.out.println(getPairs(a, n));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
using System.Collections.Generic; 
  
class GFG 
  
    // Function to return the count 
    // of unique pairs in the array 
    static int getPairs(int []a, int n) 
    
        HashSet<int> visited1 = new HashSet<int>(); 
  
        // un[i] stores number of unique elements 
        // from un[i + 1] to un[n - 1] 
        int []un = new int[n]; 
  
        // Last element will have no unique elements 
        // after it 
        un[n - 1] = 0; 
  
        // To count unique elements after every a[i] 
        int count = 0; 
        for (int i = n - 1; i > 0; i--) 
        
  
            // If current element has already been used 
            // i.e. not unique 
            if (visited1.Contains(a[i])) 
                un[i - 1] = count; 
            else
                un[i - 1] = ++count; 
  
            // Set to true if a[i] is visited 
            visited1.Add(a[i]); 
        
  
        HashSet<int> visited2 = new HashSet<int>(); 
  
        // To know which a[i] is already visited 
        int answer = 0; 
        for (int i = 0; i < n - 1; i++) 
        
  
            // If visited, then the pair would 
            // not be unique 
            if (visited2.Contains(a[i])) 
                continue
  
            // Calculating total unqiue pairs 
            answer += un[i]; 
  
            // Set to true if a[i] is visited 
            visited2.Add(a[i]); 
        
        return answer; 
    
  
    // Driver code 
    public static void Main(String[] args) 
    
        int []a = { 1, 2, 2, 4, 2, 5, 3, 5 }; 
        int n = a.Length; 
  
        // Print the count of unique pairs 
        Console.WriteLine(getPairs(a, n)); 
    
  
/* This code contributed by PrinciRaj1992 */

chevron_right


Output:

14

Time Complexity: O(n)



My Personal Notes arrow_drop_up

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.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.