Count elements such that there are exactly X elements with values greater than or equal to X | JavaScript implementation of the approach ; Sorting the vector ; Count of numbers which are greater than v [ i ] ; Function to implement upper_bound ( ) ; Driver Code
function getCount ( v , n ) { v . sort ( function ( a , b ) { return a - b ; } ) ; let cnt = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let tmp = n - 1 - upperBound ( v , n , v [ i ] - 1 ) ; if ( tmp == v [ i ] ) cnt ++ ; } return cnt ; } function upperBound ( array , length , value ) { let low = 0 ; let high = length ; while ( low < high ) { let mid = Math . floor ( ( low + high ) / 2 ) ; if ( value >= array [ mid ] ) { low = mid + 1 ; } else { high = mid ; } } return low ; } let n = 4 ; let v = [ 1 , 2 , 3 , 4 ] ; document . write ( getCount ( v , n ) ) ;