After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them
while ( s . length != 0 ) { mp [ s [ s . length - 1 ] ] = - 1 ; s . pop ( ) ; } for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " + mp [ arr [ i ] ] + " " ) ; }