Number of NGEs to the right |  ; use of stl stack in Java ; 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
import java . util . * ; class GFG { static Vector < Integer > no_NGN ( int arr [ ] , int n ) { Vector < Integer > nxt = new Vector < > ( ) ; Stack < Integer > s = new Stack < > ( ) ; nxt . add ( 0 ) ; s . add ( n - 1 ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { while ( ! s . isEmpty ( ) && arr [ i ] >= arr [ s . peek ( ) ] ) s . pop ( ) ; if ( s . isEmpty ( ) ) nxt . add ( 0 ) ; else nxt . add ( nxt . get ( n - s . peek ( ) - 1 ) + 1 ) ; s . add ( i ) ; } Collections . reverse ( nxt ) ; return nxt ; } public static void main ( String [ ] args ) { int n = 8 ; int arr [ ] = { 3 , 4 , 2 , 7 , 5 , 8 , 10 , 6 } ; Vector < Integer > nxt = no_NGN ( arr , n ) ; System . out . print ( nxt . get ( 3 ) + "NEW_LINE"); System . out . print ( nxt . get ( 6 ) + "NEW_LINE"); System . out . print ( nxt . get ( 1 ) + "NEW_LINE"); } }