Given two integers N and K. The task is to print the lexicographically smallest string of length N consisting of lower-case English alphabates such that the sum of the characters of the string equals to K where ‘a’ = 1, ‘b’ = 2, ‘c’ = 3, ….. and ‘z’ = 26.
Input: N = 5, K = 42
“aaany”, “babmx”, “aablz” etc. are also valid strings
but “aaamz” is the lexicographically smallest.
Input: N = 3, K = 25
- Initialize char array of size N and fill all the element by ‘a’.
- Start traversing from the end of the array and replace the elements of the array by ‘z’ if K ≥ 26 or replace it by the character having ASCII value (K + 97 – 1).
- At the same time decrease the value of K by replaced element value i.e. for a = 1, b = 2, c = 3, …, z = 26.
- Also, note that we are subtracting previous element value i.e. (total ‘a’) before current element and adding the same before the end of for loop.
- Check for K < 0 condition and break the for loop.
- Return the new string formed by the elements of the char array as the answer.
Below is the implementation of the above approach:
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Queries to answer the X-th smallest sub-string lexicographically
- K-th lexicographically smallest unique substring of a given string
- Lexicographically smallest permutation of a string with given subsequences
- Find the lexicographically smallest string which satisfies the given condition
- Lexicographically smallest string obtained after concatenating array
- Swap all occurrences of two characters to get lexicographically smallest string
- Lexicographically smallest string formed by removing at most one character
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Form lexicographically smallest string with minimum replacements having equal number of 0s, 1s and 2s
- Smallest Greater (than S) String of length K whose letters are subset of S
- Length of the smallest sub-string consisting of maximum distinct characters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.