For finding next smaller element right to a element if there is no next smaller element right to it than taking n .
vector < int > nsmr ( n , n ) ; stack < int > st ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( ! st . empty ( ) && arr [ st . top ( ) ] >= arr [ i ] ) st . pop ( ) ; nsmr [ i ] = ( ! st . empty ( ) ) ? st . top ( ) : n ; st . push ( i ) ; } while ( ! st . empty ( ) ) st . pop ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! st . empty ( ) && arr [ st . top ( ) ] >= arr [ i ] ) st . pop ( ) ; nsml [ i ] = ( ! st . empty ( ) ) ? st . top ( ) : -1 ; st . push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) {