Count greater elements on the left side of every array element | Java program to implement the above approach ; Function to print the count of greater elements on left of each array element ; Function to get the count of greater elements on left of each array element ; Store distinct array elements in sorted order ; Stores the count of greater elements on the left side ; Traverse the array ; Insert array elements into the set ; Find previous greater element ; Find the distance between the previous greater element of arr [ i ] and last element of the set ; Driver code
import java . util . * ; import java . lang . * ; class GFG { static void display ( int countLeftGreater [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( countLeftGreater [ i ] + " ▁ " ) ; } } static void countGreater ( int arr [ ] , int N ) { Set < Integer > St = new TreeSet < > ( ) ; int [ ] countLeftGreater = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { St . add ( arr [ i ] ) ; int it = 0 ; Iterator < Integer > iterator = St . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( arr [ i ] < iterator . next ( ) ) { break ; } it ++ ; } countLeftGreater [ i ] = Math . abs ( it - St . size ( ) ) ; } display ( countLeftGreater , N ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 1 , 2 , 3 , 0 , 11 , 4 } ; int N = arr . length ; countGreater ( arr , N ) ; } }