Previous greater element | Java 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
import java . io . * ; import java . util . * ; import java . lang . * ; class GFG { static void prevGreater ( int arr [ ] , int n ) { Stack < Integer > s = new Stack < Integer > ( ) ; s . push ( arr [ 0 ] ) ; System . out . print ( " - 1 , ▁ " ) ; for ( int i = 1 ; i < n ; i ++ ) { while ( s . empty ( ) == false && s . peek ( ) < arr [ i ] ) s . pop ( ) ; if ( s . empty ( ) == true ) System . out . print ( " - 1 , ▁ " ) ; else System . out . print ( s . peek ( ) + " , ▁ " ) ; s . push ( arr [ i ] ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = arr . length ; prevGreater ( arr , n ) ; } }