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