Lexicographically smallest K | function for reverse ; Function to find lexicographically smallest subsequence of size K ; Length of string ; Stores the minimum subsequence ; Traverse the string S ; If the stack is empty ; Iterate till the current character is less than the the character at the top of stack ; Check if there are enough characters remaining to obtain length K ; If stack size is < K ; Push the current character into it ; Stores the resultant string ; Iterate until stack is empty ; Reverse the string ; Print the string
function reverse ( input ) { a = input ; var l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { var temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a ; } function smallestSubsequence ( S , K ) { var N = S . length ; answer = [ ] ; for ( var i = 0 ; i < N ; ++ i ) { if ( answer . length == 0 ) { answer . push ( S [ i ] ) ; } else { while ( ( answer . length != 0 ) && ( S [ i ] < answer [ answer . length - 1 ] ) && ( answer . length - 1 + N - i >= K ) ) { answer . pop ( ) ; } if ( answer . length == 0 answer . length < K ) { answer . push ( S [ i ] ) ; } } } var ret = [ ] ; while ( answer . length != 0 ) { ret += answer [ answer . length - 1 ] ; answer . pop ( ) ; } reverse ( ret ) ; document . write ( ret ) ; } var S = " " ; var K = 3 ; smallestSubsequence ( S , K ) ;