I’m using TreeSet for solving counting inversions problem. I’m using following approach which uses gnu_pbds which works in O(logn) time. Algorithm Insert the first element of the array in the Ordered_Set. 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