![]() |
VOOZH | about |
Given a string S and an integer K, the task is to find the lexicographically smallest string possible after reversing any substring of any length exactly K times.
Examples:
Input: S = "fgazcbdfge", K = 3
Output: abcdgfzfge
Explanation: After 1st operation: S = "agfzcbdfge", in S select S[0 - 2] = "fga" and reverse it
After 2nd operation: S = "abczfgdfge", in S select S[2 - 4] = "fzc" and reverse it
After 3rd operation: S = "abcdgfzfge", in S select S[3 - 6] = "zfgd" and reverse it.Input: S = "abcdefg", K = 5
Output: abcdefg
Explanation: The string is already lexicographically minimum possible.
Hence pick any 5 substrings having length 1. So the string will remain unchanged.
Approach: To form the lexicographically smallest string in K steps, in each step select an integer L where S[L] is the character before which all characters are in sorted order and an integer R where S[R] is the character which has to be placed at S[L+1] so that all character till S[L+1] will be in sorted order. Reverse the substring S[L..R] in each step and finally, the required string will be obtained. Follow the below steps to solve the problem:
Illustration:
In the above illustration, since the first three characters of the original string were in sorted order we dont have to involve them in any operation Search that character which will appear after them in the sorted order, assume it appears at index R (the character will be S[R]) we select the index of character after the first three character as R (the character will be S[R]) Now we reverse the substring S[L...R] which will result in the character S[R] to appear at S[L+1] and now the first 4 characters ofthe string S are in sorted order
Below is the implementation of the above approach.
abcdgfzfge
Time Complexity: O(K * N2) where N is the length of the string
Auxiliary Space: O(N)