Given a stringS of N characters, the task is to find the smallest lexicographical string after performing each of the following operations N times in any order:
Remove the 1st character of S and insert it into a stack X.
Remove the top of stack X and append it to the end of another string Y which is initially empty.
Input: S = “cab” Output: abc Explanation: The given string can be obtained using the following operations:
Perform operation 1. Hence, S = “ab”, X = “c”, Y = “”.
Perform operation 1. Hence, S = “b”, X = “ca”, Y = “”.
Perform operation 2. Hence, S = “b”, X = “c”, Y = “a”.
Perform operation 1. Hence, S = “”, X = “cb”, Y = “a”.
Perform operation 2. Hence, S = “”, X = “c”, Y = “ab”.
Perform operation 2. Hence, S = “”, X = “”, Y = “abc”.
Now, each of the given operations is performed N times and the string obtained is “abc” which is the smallest possible.
Input: S = “acdb” Output: abdc
Approach: The given problem can be solved using a greedy approach. The idea is to perform the 1stoperation till the top of the stack contains the smallest character after which it can be appended to the stringY. This can be efficiently done by maintaining a suffix array, where suff[i] stores the smallest ASCII value of the suffix till ith character. Below are the steps to follow:
Please Login to comment...