Stack is used to find the next smaller element and keeping track of index of current iteration
while ( stk . length != 0 && arr [ i ] < arr [ stk [ stk . length - 1 ] ] ) { minarr [ stk [ stk . length - 1 ] ] = i ; stk . pop ( ) ; } stk . push ( i ) ; }