Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2 | Java 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
import java . util . PriorityQueue ; class GFG { static String getSmallestStr ( String S , int K ) { String X = " " ; PriorityQueue < Character > pq = new PriorityQueue < > ( ) ; int i , n = S . length ( ) ; K = Math . min ( K , n ) ; for ( i = 0 ; i < K ; i ++ ) pq . add ( S . charAt ( i ) ) ; while ( ! pq . isEmpty ( ) ) { X += pq . peek ( ) ; pq . remove ( ) ; if ( i < S . length ( ) ) pq . add ( S . charAt ( i ) ) ; i ++ ; } return X ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int K = 5 ; System . out . println ( getSmallestStr ( S , K ) ) ; } }