Fill elements of right [ ] using same logic
for ( let i = n - 1 ; i >= 0 ; i -- ) { while ( s . length > 0 && arr [ s [ s . length - 1 ] ] >= arr [ i ] ) { s . pop ( ) ; } if ( s . length > 0 ) { right [ i ] = s [ s . length - 1 ] ; } s . push ( i ) ; }