After iterating over the loop , the remaining elements in stack do not have any NSE , so set - 1 for them
while ( ! s . empty ( ) ) { ans [ s . top ( ) . second ] = -1 ; s . pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " ▁ - - - > ▁ " << ans [ i ] << endl ; } }