For finding next smaller element right to a element if there is no next smaller element right to it than taking n .
let nsmr = new Array ( n ) ; nsmr . fill ( n ) ; let st = [ ] ; for ( let i = n - 1 ; i >= 0 ; i -- ) { while ( st . length > 0 && arr [ st [ st . length - 1 ] ] >= arr [ i ] ) st . pop ( ) ; nsmr [ i ] = ( st . length > 0 ) ? st [ st . length - 1 ] : n ; st . push ( i ) ; } while ( st . length > 0 ) st . pop ( ) ; for ( let i = 0 ; i < n ; i ++ ) { while ( st . length > 0 && arr [ st [ st . length - 1 ] ] >= arr [ i ] ) st . pop ( ) ; nsml [ i ] = ( st . length > 0 ) ? st [ st . length - 1 ] : - 1 ; st . push ( i ) ; } for ( let i = 0 ; i < n ; i ++ ) {