text: Lexicographically smallest K | C # program for the above approach ; 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 ; Driver Code
code: using System ; using System . Collections . Generic ; public class GFG { static void smallestSubsequence ( char [ ] S , int K ) { int N = S . Length ; Stack < char > answer = new Stack < char > ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( answer . Count == 0 ) { answer . Push ( S [ i ] ) ; } else { while ( ( answer . Count != 0 ) && ( S [ i ] < answer . Peek ( ) ) && ( answer . Count - 1 + N - i >= K ) ) { answer . Pop ( ) ; } if ( answer . Count == 0 answer . Count < K ) { answer . Push ( S [ i ] ) ; } } } String ret = " " ; while ( answer . Count != 0 ) { ret += ( answer . Peek ( ) ) ; answer . Pop ( ) ; } ret = reverse ( ret ) ; Console . Write ( ret ) ; } static String reverse ( String input ) { char [ ] a = input . ToCharArray ( ) ; int l , r = a . Length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . Join ( " " , a ) ; } public static void Main ( String [ ] args ) { String S = " aabdaabc " ; int K = 3 ; smallestSubsequence ( S . ToCharArray ( ) , K ) ; } }