Given a string str consisting of lowercase alphabets and an integer K, you can perform the following operations on str
- Initialize an empty string X = “”.
- Take any character from the first K characters of str and append it to X.
- Remove the chosen character from str.
- Repeat the above steps while there are characters left in str.
The task is to generate X such that it is lexicographically smallest possible then print the generated string.
Input: str = “geek”, K = 2
Operation 1: str = “gek”, X = “e”
Operation 2: str = “gk”, X = “ee”
Operation 3: str = “k”, X = “eeg”
Operation 4: str = “”, X = “eegk”
Input: str = “geeksforgeeks”, K = 5
Approach: In order to get the lexicographically smallest string, we need to take the minimum character from the first K characters every time we choose a character from str. To do that, we can put the first K characters in a priority_queue (min-heap) and then choose the smallest character and append it to X. Then, push the next character in str to the priority queue and repeat the process until there are characters left to process.
Below is the implementation of the above approach:
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by removing at most one character
- Lexicographically largest string formed from the characters in range L and R
- Swap all occurrences of two characters to get lexicographically smallest string
- Minimal moves to form a string by adding characters or appending string itself
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Count of times second string can be formed from the characters of first string
- Find a string such that every character is lexicographically greater than its immediate next character
- Check whether second string can be formed from characters of first string
- Find the smallest window in a string containing all characters of another string
- Lexicographically next greater string using same character set
- Lexicographically smallest string of length N and sum K
- Lexicographically smallest permutation of a string with given subsequences
- K-th lexicographically smallest unique substring of a given string
- Queries to answer the X-th smallest sub-string lexicographically
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sanjeev2552