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


In this tutorial, we will be discussing a program to count smaller elements on right side using set in C++ STL.

For this we will be provided with an array. Our task is to construct a new array and add the number of smaller elements on the right side of the current element at its position.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void count_Rsmall(int A[], int len){
   set<int> s;
   int countSmaller[len];
   for (int i = len - 1; i >= 0; i--) {
      s.insert(A[i]);
      auto it = s.lower_bound(A[i]);
      countSmaller[i] = distance(s.begin(), it);
   }
   for (int i = 0; i < len; i++)
      cout << countSmaller[i] << " ";
}
int main(){
   int A[] = {12, 1, 2, 3, 0, 11, 4};
   int len = sizeof(A) / sizeof(int);
   count_Rsmall(A, len);
   return 0;
}

Output

6 1 1 1 0 1 0

Updated on: 16-Mar-2020

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements