Count smaller elements on right side using Set in C++ STL

Write a function to count number of smaller elements on right of each element in an array. Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains count of smaller elements on right side of each element arr[i] in array.

Input : arr[] =  {12, 1, 2, 3, 0, 11, 4}
Output :countSmaller[]  =  {6, 1, 1, 1, 0, 1, 0} 

Input :arr[]={5, 4, 3, 2, 1}
Output :countSmaller[]={4, 3, 2, 1, 0}

In this post an easy implementation of is discussed.

Create an empty Set in C++ STL (Note that Set in C++ STL is implemented Self Balancing Binary Search Tree).

  1. Traverse the array element from i=len-1 to 0 and insert every element in a set.
  2. Find the first element that is lower than A[i] using lower_bound function.
  3. Find the distance between above found element and the beginning of the set using distance function.
  4. Store the distance in another array Lets say CountSmaller.
  5. Print that array .

[sourcecode language=”CPP”]
// CPP program to find count of smaller
// elements on right side using set in C++
// STL.
#include <bits/stdc++.h>
using namespace std;
void countSmallerRight(int A[], int len)
set<int> s;
int countSmaller[len];
for (int i = len – 1; i >= 0; i–) {
auto it = s.lower_bound(A[i]);
countSmaller[i] = distance(s.begin(), it);

for (int i = 0; i < len; i++)
cout << countSmaller[i] << " ";

// Driver code
int main()
int A[] = {12, 1, 2, 3, 0, 11, 4};
int len = sizeof(A) / sizeof(int);
countSmallerRight(A, len);
return 0;


6 1 1 1 0 1 0

Note that the above implementation takes worst case time complexity O(n^2) as the worst case time complexity of distance function is O(n) but the above implementation is very simple and works better than naive algorithm in average case.

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 or mail your article to 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 to report any issue with the above content.