Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string.
- In each operation, select one character optimally from the string and update it with immediate next character ( aaa -> aab ), so that string remain lexicographical smallest.
- Multiple operations are allowed over single character of the string.
Note: Consider next of ‘z’ as ‘a’.
Input: S = “aazzx”, M = 6
We try to form lexicographical smallest string for each operations.
For m = 1: update “aazzx” to “aaazx”
for m = 2: update “aaazx” to “aaaax”
for m = 3: update “aaaax” to “aaaay”
for m = 4: update “aaaay” to “aaaaz”
for m = 5: update “aaaaz” to “aaaaa”
for m = 6: update “aaaaa” to “aaaab” which is lexicographical smallest than “aaaba”, “aabaa”, “abaaa”, “baaaa”.
Final string after 6 operations: “aaaab”.
Input: S = “z”, M = 27
Try to form lexicographical smallest string for each operations, since there is only single character so all 27 operations have to performed over it. Final string after 27 operation is “a”.
Approach: The idea is to implement a simple greedy approach, to iterate the string from the starting of the string and while iterating focus on the current element of the string to make it as small as possible.
- Suppose, current element is r, to make r smallest i.e. a, it require 9 operations, let call the value as distance.
- Now, check if M is greater than equal to the distance, then update current character to ‘a’ and decrease the value of M by distance. Otherwise continue with next iteration.
- As next of z is a, cycle of 26 is formed. So the last character of the string, can be updated with last character + (M % 26).
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of given string
Auxiliary Space: O(N), where N is the length of given string
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.