Fill elements of left [ ] using logic discussed on www . geeksforgeeks . org / next - greater - element / https :
for ( let i = 0 ; i < n ; i ++ ) { while ( s . length > 0 && arr [ s [ s . length - 1 ] ] >= arr [ i ] ) { s . pop ( ) ; } if ( s . length > 0 ) { left [ i ] = s [ s . length - 1 ] ; } s . push ( i ) ; }