Find the next greater element in a Circular Array | Set 2 | Function to find the NGE for the given circular array [ ] arr ; Initialize stack and nge [ ] array ; Initialize nge [ ] array to - 1 ; Traverse the array ; If stack is not empty and current element is greater than top element of the stack ; Assign next greater element for the top element of the stack ; Pop the top element of the stack ; Print the nge [ ] array ; Driver Code ; Function Call
function printNGE ( arr , n ) { let s = [ ] ; let nge = new Array ( n ) ; let i = 0 ; for ( i = 0 ; i < n ; i ++ ) { nge [ i ] = - 1 ; } i = 0 ; while ( i < 2 * n ) { while ( s . length != 0 && arr [ i % n ] > arr [ s [ s . length - 1 ] ] ) { nge [ s [ s . length - 1 ] ] = arr [ i % n ] ; s . pop ( ) ; } s . push ( i % n ) ; i ++ ; } for ( i = 0 ; i < n ; i ++ ) { document . write ( nge [ i ] + " " ) ; } } let arr = [ 4 , - 2 , 5 , 8 ] ; let N = arr . length ; printNGE ( arr , N ) ;