Next Smaller Element | A Stack based C # program to find next smaller element for all array elements in same order as input . using System ; ; prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ; Driver Code
using System ; using System . Collections . Generic ; class GFG { public static void printNSE ( int [ ] arr , int n ) { Stack < int > s = new Stack < int > ( ) ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; s . Push ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s . Count == 0 ) { s . Push ( arr [ i ] ) ; continue ; } while ( s . Count != 0 && s . Peek ( ) > arr [ i ] ) { mp . Add ( s . Peek ( ) , arr [ i ] ) ; s . Pop ( ) ; } s . Push ( arr [ i ] ) ; } while ( s . Count != 0 ) { mp . Add ( s . Peek ( ) , - 1 ) ; s . Pop ( ) ; } for ( int i = 0 ; i < n ; i ++ ) Console . WriteLine ( arr [ i ] + " ▁ - - - > ▁ " + mp [ arr [ i ] ] ) ; } public static void Main ( ) { int [ ] arr = { 11 , 13 , 21 , 3 } ; int n = arr . Length ; printNSE ( arr , n ) ; } }