Previous greater element | Python 3 program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver code
def prevGreater ( arr , n ) : NEW_LINE INDENT print ( " - 1" , end = " , ▁ " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ j ] : NEW_LINE INDENT print ( arr [ j ] , end = " , ▁ " ) NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if j == 0 and flag == 0 : NEW_LINE INDENT print ( " - 1" , end = " , ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE prevGreater ( arr , n ) NEW_LINE DEDENT