Count of pairs (x, y) in an array such that x < y - GeeksforGeeks

01 Jun, 2021
Given an array of N distinct integers, the task is to find the number of pairs (x, y) such that x < y.
Example:  
Input: arr[] = {2, 4, 3, 1} Output: 6 Possible pairs are (1, 2), (1, 3), (1, 4), (2, 3), (2, 4) and (3, 4).Input: arr[] = {5, 10} Output: 1 The only possible pair is (5, 10). 
Naive approach: Find every possible pair and check whether it satisfies the given condition or not. 
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[],int n){    // To store the number of valid pairs    int count = 0;    for (int i = 0; i < n; i++)    {        for (int j = 0; j < n; j++)        {             // If a valid pair is found            if (a[i] < a[j])                count++;        }    }     // Return the count of valid pairs    return count;} // Driver codeint main(){    int a[] = { 2, 4, 3, 1 };    int n = sizeof(a) / sizeof(a[0]);    cout << getPairs(a, n);    return 0;}     // This code is contributed by SHUBHAMSINGH10
// Java implementation of the approachclass GFG {     // Function to return the number of    // pairs (x, y) such that x < y    static int getPairs(int a[])    {        // To store the number of valid pairs        int count = 0;        for (int i = 0; i < a.length; i++) {            for (int j = 0; j < a.length; j++) {                 // If a valid pair is found                if (a[i] < a[j])                    count++;            }        }         // Return the count of valid pairs        return count;    }     // Driver code    public static void main(String[] args)    {        int a[] = { 2, 4, 3, 1 };        System.out.println(getPairs(a));    }}
# Python3 implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a):         # To store the number of valid pairs    count = 0    for i in range(len(a)):        for j in range(len(a)):             # If a valid pair is found            if (a[i] < a[j]):                count += 1     # Return the count of valid pairs    return count # Driver codeif __name__ == "__main__":     a = [ 2, 4, 3, 1 ]    print(getPairs(a)) # This code is contributed by ita_c
// C# implementation of the approachusing System; class GFG{     // Function to return the number of    // pairs (x, y) such that x < y    static int getPairs(int []a)    {        // To store the number of valid pairs        int count = 0;        for (int i = 0; i < a.Length; i++)        {            for (int j = 0; j < a.Length; j++)            {                 // If a valid pair is found                if (a[i] < a[j])                    count++;            }        }         // Return the count of valid pairs        return count;    }     // Driver code    public static void Main()    {        int []a = { 2, 4, 3, 1 };        Console.WriteLine(getPairs(a));    }} // This code is contributed by Ryuga
<?php// PHP implementation of the approach // Function to return the number of// pairs (x, y) such that x < yfunction getPairs($a){    // To store the number of valid pairs    $count = 0;    for ($i = 0; $i < sizeof($a); $i++)    {        for ($j = 0; $j < sizeof($a); $j++)        {             // If a valid pair is found            if ($a[$i] < $a[$j])                $count++;        }    }     // Return the count of valid pairs    return $count;} // Driver code$a = array(2, 4, 3, 1);echo getPairs($a); // This code is contributed// by Akanksha Rai?>
<script>// Javascript implementation of the approach     // Function to return the number of    // pairs (x, y) such that x < y    function getPairs(a)    {        // To store the number of valid pairs        let count = 0;        for (let i = 0; i < a.length; i++) {            for (let j = 0; j < a.length; j++) {                   // If a valid pair is found                if (a[i] < a[j])                    count++;            }        }           // Return the count of valid pairs        return count;    }         // Driver code    let a=[ 2, 4, 3, 1 ];    document.write(getPairs(a));             // This code is contributed by rag2127</script>
6
 
Time Complexity: O(n2)
Efficient approach: For an element x. In order to find the count of valid pairs of the form (x, y1), (x, y2), ..., (x, yn), we need to count the elements which are greater than x. For the smallest element, there will be n – 1 element greater than it. Similarly, the second smallest element can form n – 2 pairs and so on. Therefore, the desired count of valid pairs will be (n – 1) + (n – 2) + .... + 1 = n * (n – 1) / 2 where n is the length of the array. 
Below is the implementation of the above approach: 
C++
Java
Python
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// pairs (x, y) such that x < yint getPairs(int a[]){    // Length of the array    int n = sizeof(a[0]);         // Calculate the number valid pairs    int count = (n * (n - 1)) / 2;     // Return the count of valid pairs    return count;} // Driver codeint main(){    int a[] = { 2, 4, 3, 1 };    cout << getPairs(a);    return 0;} // This code is contributed// by SHUBHAMSINGH10
// Java implementation of the approachclass GFG {     // Function to return the number of    // pairs (x, y) such that x < y    static int getPairs(int a[])    {        // Length of the array        int n = a.length;         // Calculate the number of valid pairs        int count = (n * (n - 1)) / 2;         // Return the count of valid pairs        return count;    }     // Driver code    public static void main(String[] args)    {        int a[] = { 2, 4, 3, 1 };        System.out.println(getPairs(a));    }}
# Python implementation of the approach # Function to return the number of# pairs (x, y) such that x < ydef getPairs(a):         # Length of the array    n = len(a)         # Calculate the number of valid pairs    count = (n * (n - 1)) // 2         # Return the count of valid pairs    return count     # Driver codea = [2, 4, 3, 1]print(getPairs(a)) # This code is contributed by SHUBHAMSINGH10
// C# implementation of the approachusing System;class GFG{     // Function to return the number of    // pairs (x, y) such that x < y    static int getPairs(int []a)    {        // Length of the array        int n = a.Length;         // Calculate the number of valid pairs        int count = (n * (n - 1)) / 2;         // Return the count of valid pairs        return count;    }     // Driver code    public static void Main()    {        int []a = { 2, 4, 3, 1 };        Console.Write(getPairs(a));    }} // This code is contributed// by Akanksha Rai
<script>     // JavaScript implementation of the approach         // Function to return the number of    // pairs (x, y) such that x < y    function getPairs(a)    {        // Length of the array        let n = a.length;          // Calculate the number of valid pairs        let count = parseInt((n * (n - 1)) / 2, 10);          // Return the count of valid pairs        return count;    }         let a = [ 2, 4, 3, 1 ];      document.write(getPairs(a));     </script>
6
 
Time Complexity: O(1) 
ankthon
ukasp
Akanksha_Rai
SHUBHAMSINGH10
rag2127
mukesh07
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7