Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2 | C ++ implementation of the approach ; Function to return the lexicographically smallest required string ; Initially empty string ; min heap of characters ; Length of the string ; K cannot be greater than the size of the string ; First push the first K characters into the priority_queue ; While there are characters to append ; Append the top of priority_queue to X ; Remove the top element ; Push only if i is less than the size of string ; Return the generated string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getSmallestStr ( string S , int K ) { string X = " " ; priority_queue < char , vector < char > , greater < char > > pq ; int i , n = S . length ( ) ; K = min ( K , n ) ; for ( i = 0 ; i < K ; i ++ ) pq . push ( S [ i ] ) ; while ( ! pq . empty ( ) ) { X += pq . top ( ) ; pq . pop ( ) ; if ( i < S . length ( ) ) pq . push ( S [ i ] ) ; i ++ ; } return X ; } int main ( ) { string S = " geeksforgeeks " ; int K = 5 ; cout << getSmallestStr ( S , K ) ; return 0 ; }