Number of unique pairs in an array

30 Jun, 2021
Given an array of N elements, the task is to find all the unique pairs that can be formed using the elements of a given array. Examples: 
Input: arr[] = {1, 1, 2} Output: 4 (1, 1), (1, 2), (2, 1), (2, 2) are the only possible pairs.
Input: arr[] = {1, 2, 3} Output: 9 
Naive approach: The simple solution is to iterate through every possible pair and add them to a set and then find out the size of the set.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of unique pairs in the arrayint countUnique(int arr[], int n){     // Set to store unique pairs    set<pair<int, int> > s;     // Make all possible pairs    for (int i = 0; i < n; i++)        for (int j = 0; j < n; j++)            s.insert(make_pair(arr[i], arr[j]));     // Return the size of the set    return s.size();} // Driver codeint main(){    int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << countUnique(arr, n);    return 0;}
// Java implementation of the approachimport java.awt.Point;import java.util.*; class GFG{ // Function to return the number// of unique pairs in the arraystatic int countUnique(int arr[], int n){     // Set to store unique pairs    Set<Point> s = new HashSet<>();     // Make all possible pairs    for (int i = 0; i < n; i++)        for (int j = 0; j < n; j++)            s.add(new Point(arr[i], arr[j]));     // Return the size of the set    return s.size();} // Driver codepublic static void main(String[] args){    int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 };    int n = arr.length;     System.out.print(countUnique(arr, n));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n):    # Set to store unique pairs    s = set()     # Make all possible pairs    for i in range(n):        for j in range(n):            s.add((arr[i], arr[j]))     # Return the size of the set    return len(s)  # Driver code arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]n = len(arr)print(countUnique(arr, n)) # This code is contributed by ankush_953
// C# implementation of the approachusing System;using System.Collections;using System.Collections.Generic; class GFG{     public class store : IComparer<KeyValuePair<int, int>>{    public int Compare(KeyValuePair<int, int> x,                       KeyValuePair<int, int> y)    {        if (x.Key != y.Key)        {            return x.Key.CompareTo(y.Key);           }        else        {            return x.Value.CompareTo(y.Value);           }    }}     // Function to return the number// of unique pairs in the arraystatic int countUnique(int []arr, int n){         // Set to store unique pairs    SortedSet<KeyValuePair<int,                           int>> s = new  SortedSet<KeyValuePair<int,                                                                 int>>(new store());       // Make all possible pairs    for(int i = 0; i < n; i++)        for(int j = 0; j < n; j++)            s.Add(new KeyValuePair<int, int>(arr[i], arr[j]));       // Return the size of the set    return s.Count;} // Driver code   public static void Main(string []arg){    int []arr = { 1, 2, 2, 4, 2, 5, 3, 5 };    int n = arr.Length;         Console.Write(countUnique(arr, n));}} // This code is contributed by rutvik_56
<script>     // JavaScript implementation of the approach     // Function to return the number    // of unique pairs in the array    function countUnique(arr,n)    {         // Set to store unique pairs        let s = new Set();         // Make all possible pairs        for (let i = 0; i < n; i++)            for (let j = 0; j < n; j++)                s.add((arr[i], arr[j]));         // Return the size of the set        return 5*s.size;    }     // Driver code    let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ];    let n = arr.length;     document.write(countUnique(arr, n));     </script>
25
 
Time Complexity: Time complexity of the above implementation is O(n2 Log n). We can optimize it to O(n2) using unordered_set with user defined hash function.
Efficient approach: First find out the number of unique elements in an array. Let the number of unique elements be x. Then, the number of unique pairs would be x2. This is because each unique element can form a pair with every other unique element including itself.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number// of unique pairs in the arrayint countUnique(int arr[], int n){     unordered_set<int> s;    for (int i = 0; i < n; i++)        s.insert(arr[i]);     int count = pow(s.size(), 2);     return count;} // Driver codeint main(){    int arr[] = { 1, 2, 2, 4, 2, 5, 3, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << countUnique(arr, n);    return 0;}
// Java implementation of the approachimport java.util.*; class GFG{     // Function to return the number    // of unique pairs in the array    static int countUnique(int arr[], int n)    {         HashSet<Integer> s = new HashSet<>();        for (int i = 0; i < n; i++)        {            s.add(arr[i]);        }        int count = (int) Math.pow(s.size(), 2);         return count;    }     // 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(countUnique(arr, n));    }} /* This code has been contributedby PrinciRaj1992*/
# Python3 implementation of the approach # Function to return the number# of unique pairs in the arraydef countUnique(arr, n):         s = set()    for i in range(n):        s.add(arr[i])     count = pow(len(s), 2)     return count # Driver codeif __name__ == "__main__" :     arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ]    n = len(arr)     print(countUnique(arr, n))     # This code is contributed by Ryuga
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{     // Function to return the number    // of unique pairs in the array    static int countUnique(int []arr, int n)    {         HashSet<int> s = new HashSet<int>();        for (int i = 0; i < n; i++)        {            s.Add(arr[i]);        }        int count = (int) Math.Pow(s.Count, 2);         return count;    }     // Driver code    static void Main()    {        int []arr = {1, 2, 2, 4, 2, 5, 3, 5};        int n = arr.Length;        Console.WriteLine(countUnique(arr, n));    }} // This code has been contributed by mits
<script> // JavaScript Program to implement// the above approach      // Function to return the number    // of unique pairs in the array    function countUnique(arr, n){         let s = new Set();        for (let i = 0; i < n; i++)        {            s.add(arr[i]);        }        let count = Math.pow(s.size, 2);         return count;    }// Driver Code     let arr = [ 1, 2, 2, 4, 2, 5, 3, 5 ];    let n = arr.length;      document.write(countUnique(arr, n)); </script>
25
 
Time Complexity: O(n) 
princiraj1992
ankthon
Mithun Kumar
ankush_953
29AjayKumar
rutvik_56
aniruddhkotte
susmitakundugoaldanga
vaibhavrabadiya117
cpp-unordered_set
Arrays
Combinatorial
Hash
Arrays
Hash
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Write a program to print all permutations of a given string
Permutation and Combination in Python
Count of subsets with sum equal to X
Factorial of a large number