Next Smaller Element | 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
function printNSE ( arr , n ) { let s = [ ] ; let mp = new Map ( ) ; s . push ( arr [ 0 ] ) ; for ( let i = 1 ; i < n ; i ++ ) { if ( s . length == 0 ) { s . push ( arr [ i ] ) ; continue ; } while ( s . length != 0 && s [ s . length - 1 ] > arr [ i ] ) { mp [ s [ s . length - 1 ] ] = arr [ i ] ; s . pop ( ) ; } s . push ( arr [ i ] ) ; } 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 ] ] + " " ) ; } let arr = [ 11 , 13 , 21 , 3 ] ; let n = arr . length ; printNSE ( arr , n ) ;