Open In App

Counting Inversions using Ordered Set and GNU C++ PBDS

Last Updated : 22 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers. The task is to find the number of inversion. Two elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j

Examples 

Input: arr[] = {8, 4, 2, 1} 
Output:
Explanation: 
Given array has six inversions:  

  • (8, 4): arr[0] > arr[1] and 0 < 1
  • (8, 2): arr[0] > arr[2] and 0 < 2
  • (8, 1): arr[0] > arr[3] and 0 < 3
  • (4, 2): arr[1] > arr[2] and 1 < 2
  • (4, 1): arr[1] > arr[3] and 1 < 3
  • (2, 1): arr[2] > arr[3] and 2 < 3

Input: arr[] = {2, 3} 
Output:
Explanation: 
There is no such pair exists such that arr[i] > arr[j] and i < j.
 

We have already discussed below approaches:  

In this post, we will be discussing an approach using Ordered Set and GNU C++ PBDS.

Approach: 
We will be using the function order_of_key(K) which returns number of elements strictly smaller than K in log N time.  

  1. Insert the first element of the array in the Ordered_Set.
  2. For all the remaining element in arr[] do the following: 
    • Insert the current element in the Ordered_Set.
    • Find the number of element strictly less than current element + 1 in Ordered_Set using function order_of_key(arr[i]+1).
    • The difference between size of Ordered_Set and order_of_key(current_element + 1) will give the inversion count for the current element.

For Example:

arr[] = {8, 4, 2, 1}
Ordered_Set S = {8}
For remaining element in arr[]:
At index 1, the element is  4
S = {4, 8}
key = order_of_key(5) = 1
The difference between size of S and key gives the total 
number of inversion count for that current element.
inversion_count = S.size() - key =  2 - 1 = 1
Inversion Pairs are: (8, 4)

At index 2, the element is  2
S = {2, 4, 8}
key = order_of_key(3) = 1
inversion_count = S.size() - key =  3 - 1 = 2
Inversion Pairs are: (8, 2) and (4, 2)

At index 3, the element is 1
S = {1, 2, 4, 8}
key = order_of_key(2) = 1
inversion_count = S.size() - key =  4 - 1 = 3
Inversion Pairs are: (8, 1), (4, 1) and (2, 1)

Total inversion count = 1 + 2 + 3 = 6

Below is the implementation of the above approach: 

C++




// Ordered set in GNU C++ based
// approach for inversion count
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
 
// Ordered Set Tree
typedef tree<int, null_type, less_equal<int>,
             rb_tree_tag,
             tree_order_statistics_node_update>
    ordered_set;
 
// Returns inversion count in
// arr[0..n-1]
int getInvCount(int arr[], int n)
{
    int key;
    // Initialise the ordered_set
    ordered_set set1;
 
    // Insert the first
    // element in set
    set1.insert(arr[0]);
 
    // Initialise inversion
    // count to zero
    int invcount = 0;
 
    // Finding the inversion
    // count for current element
    for (int i = 1; i < n; i++) {
        set1.insert(arr[i]);
 
        // Number of elements strictly
        // less than arr[i]+1
        key = set1.order_of_key(arr[i] + 1);
 
        // Difference between set size
        // and key will give the
        // inversion count
        invcount += set1.size() - key;
    }
    return invcount;
}
 
// Driver's Code
int main()
{
    int arr[] = { 8, 4, 2, 1 };
    int n = sizeof(arr) / sizeof(int);
 
    // Function call to count
    // inversion
    cout << getInvCount(arr, n);
    return 0;
}


Output: 

6

 

Time Complexity: O(Nlog N)
 



Similar Reads

Ordered Set and GNU C++ PBDS
Prerequisite :Basic knowledge of STL and Sets Data structure. About ordered set Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted order. It performs all the operations as performed by the set data structure in STL in log(n) complexity and performs two additional operations also in log(n) complexity . order
7 min read
Php Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)
Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i Example:  Input: arr[] =
2 min read
C++ Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)
Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i Example:  Input: arr[] =
6 min read
Javascript Program For Counting Inversions In An Array - Set 1 (Using Merge Sort)
Inversion Count for an array indicates - how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i Example:  Input: arr[] =
5 min read
Counting inversions in an array using segment tree
Given an array of integers arr, the task is to count the number of inversions in the array. If A[i] &gt; A[j] and i &lt; j then the pair (A[i], A[j]) is part of an inversion. Examples: Input: arr[] = {8, 4, 2, 1} Output: 6 Input: arr[] = {3, 1, 2} Output: 2 Approach: Build a segment tree where each node will represent the total numbers present in t
10 min read
Counting inversions in an subarrays
Given an array arr[], the goal is to count the number of inversions in all the sub-arrays. An inversion is a pair of indices i and j such that i &gt; j and arr[i] &lt; arr[j]. A sub-array from index x to y ( x&lt;= y) consists of the element's arr[x], arr[x+1], ..., arr[y]. The array arr[] can also contain repeated elements. Examples: Input: arr[]
18 min read
Counting segment inversions of an Array with updates
Given an array of small integers arr[] and a 2D array of queries[][], In each query array we have the first element indicating the operation type, and the remaining elements are the arguments. If query[i][0] is '1' then query[i][1] = l and query[i][2] = r and we have to Find the number of inversions in the segment from l to r (inclusive) of the arr
16 min read
Counting inversions in all subarrays of given size
Given an array and an integer k, count all inversions in all subarrays of size k. Example: Input : a[] = {7, 3, 2, 4, 1}, k = 3; Output : 6 Explanation: subarrays of size 3 are - {7, 3, 2} {3, 2, 4} {2, 4, 1} and there inversion count are 3, 1, 2 respectively. So, total number of inversions are 6. It is strongly recommended referring Inversion coun
18 min read
Interval Tree using GNU Tree-based container
Consider a situation where we have a set of intervals and we need the following operations to be implemented efficiently:  Add an intervalRemove an intervalGiven an interval x, find if x overlaps with any of the existing intervals.An Interval Tree can be implemented as an augmented binary-search tree (preferably self-balancing), and thus enable us
16 min read
Count inversions in an array | Set 4 ( Using Trie )
Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] &gt; a[j] and i &lt; j. For simplicity, we may assume that all element
12 min read