For finding next smaller element right to a element if there is no next smaller element right to it than taking n .
nsmr = [ n for i in range ( n ) ] NEW_LINE st = [ ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( len ( st ) > 0 and arr [ st [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT nsmr [ i ] = st [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nsmr [ i ] = n NEW_LINE DEDENT st . append ( i ) NEW_LINE DEDENT while ( len ( st ) > 0 ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT while ( len ( st ) > 0 and arr [ st [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT nsml [ i ] = st [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nsml [ i ] = - 1 NEW_LINE DEDENT st . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE