Previous greater element | Javascript program 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
function prevGreater ( arr , n ) { let s = [ ] ; s . push ( arr [ 0 ] ) ; document . write ( " " ) ; for ( let i = 1 ; i < n ; i ++ ) { while ( s . length != 0 && s [ s . length - 1 ] < arr [ i ] ) s . pop ( ) ; if ( s . length == 0 ) document . write ( " " ) ; else document . write ( s [ s . length - 1 ] + " " ) ; s . push ( arr [ i ] ) ; } } let arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] ; let n = arr . length ; prevGreater ( arr , n ) ;