Given a number K and a string S, We have to Find the lexicographically smallest string str of length K such that it’s set of letters is a subset of the set of letters of S and S is lexicographically smaller than str.
Input :k = 3 s = zbf Output: zbz Explanation: zbz is greater than zbf and it is smaller than any other lexicographically greater string than zbf Input :k = 3 s = gi Output: gig Explanation: gig > gi and size is 3.
Approach: If size of string is less than k, we should simply add k – s.size() minimum symbols from s.
If the size of the string is greater then or equal to k then we need to replace all symbols in the suffix of first k symbols of string smallest symbols and replace the character before this suffix with next greater character existing in the string.
Note: If k – 1 index in string holds the greatest character then we move one index back and we move back until we find a character which is not equal to the greatest character.
Time Complexity : O(k + s.size())
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Find a string such that every character is lexicographically greater than its immediate next character
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smaller string by swapping at most one character pair
- Lexicographically smallest string formed by removing at most one character
- Make the string lexicographically smallest and non palindromic by replacing exactly one character
- Lexicographically largest subsequence such that every character occurs at least k times
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Replace every character of string by character whose ASCII value is K times more than it
- Modify the string such that every character gets replaced with the next character in the keyboard
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Smallest alphabet greater than a given character
- Map every character of one string to another such that all occurrences are mapped to the same character
- Lexicographically next string
- Lexicographically first palindromic string
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.