Find the next greater element in a Circular Array | Set 2 | Function to find the NGE for the given circular array arr [ ] ; create stack list ; 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
def printNGE ( arr , n ) : NEW_LINE INDENT s = [ ] ; NEW_LINE nge = [ - 1 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( i < 2 * n ) : NEW_LINE INDENT while ( len ( s ) != 0 and arr [ i % n ] > arr [ s [ - 1 ] ] ) : NEW_LINE INDENT nge [ s [ - 1 ] ] = arr [ i % n ] ; NEW_LINE s . pop ( ) ; NEW_LINE DEDENT s . append ( i % n ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( nge [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , - 2 , 5 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE printNGE ( arr , N ) ; NEW_LINE DEDENT