Previous greater element | Python3 program to print previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver code
import math as mt NEW_LINE def prevGreater ( arr , n ) : NEW_LINE INDENT s = list ( ) ; NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE print ( " - 1 , ▁ " , end = " " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( len ( s ) > 0 and s [ - 1 ] < arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ( s ) == 0 : NEW_LINE INDENT print ( " - 1 , ▁ " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ - 1 ] , " , ▁ " , end = " " ) NEW_LINE DEDENT s . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE prevGreater ( arr , n ) NEW_LINE