If NG [ i ] = = - 1 then there is no smaller element on right side . We can find Right smaller of next greater by arr [ RS [ NG [ i ] ] ]
for ( let i = 0 ; i < arr . length ; i ++ ) { if ( NG [ i ] != - 1 && RS [ NG [ i ] ] != - 1 ) document . write ( arr [ RS [ NG [ i ] ] ] + " " ) ; else document . write ( " " ) ; } }