Count smaller elements present in the array for each array element | Function to count for each array element , the number of elements that are smaller than that element ; Stores the frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Initialize sum with 0 ; Compute prefix sum of the array hash [ ] ; Traverse the array arr [ ] ; If current element is 0 ; Print the resultant count ; Driver Code
function smallerNumbers ( arr , N ) { let hash = new Array ( 100000 ) ; hash . fill ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) hash [ arr [ i ] ] ++ ; let sum = 0 ; for ( let i = 1 ; i < 100000 ; i ++ ) { hash [ i ] += hash [ i - 1 ] ; } for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 0 ) { document . write ( " " + " " ) ; continue ; } document . write ( hash [ arr [ i ] - 1 ] + " " ) ; } } let arr = [ 3 , 4 , 1 , 1 , 2 ] ; let N = arr . length ; smallerNumbers ( arr , N ) ;