Number of NGEs to the right |  ; use of stl stack in c ++ ; push the ( n - 1 ) th index to the stack ; traverse in reverse order ; if no element is greater than arr [ i ] the number of NGEs to right is 0 ; number of NGEs to right of arr [ i ] is one greater than the number of NGEs to right of higher number to its right ; reverse again because values are in reverse order ; returns the vector of number of next greater elements to the right of each index . ; Driver code ; query 1 answered ; query 2 answered ; query 3 answered
function no_NGN ( arr , n ) { var nxt = [ ] ; var s = [ ] ; nxt . push ( 0 ) ; s . push ( n - 1 ) ; for ( var i = n - 2 ; i >= 0 ; i -- ) { while ( s . length != 0 && arr [ i ] >= arr [ s [ s . length - 1 ] ] ) s . pop ( ) ; if ( s . length == 0 ) nxt . push ( 0 ) ; else nxt . push ( nxt [ n - s [ s . length - 1 ] - 1 ] + 1 ) ; s . push ( i ) ; } nxt . reverse ( ) ; return nxt ; } var n = 8 ; var arr = [ 3 , 4 , 2 , 7 , 5 , 8 , 10 , 6 ] ; var nxt = no_NGN ( arr , n ) ; document . write ( nxt [ 3 ] + " " ) ; document . write ( nxt [ 6 ] + " " ) ; document . write ( nxt [ 1 ] + " " ) ;