Solution

To get the lexicographically smallest string possible we need to have maximum smallest characters in the beginning succeeded by the next smallest and so on. Meaning it should be sorted in non decreasing order.

Example : dsdcacdfac

ideally the smallest that we would like is aacccdddfs we will see if this achievable or not later.

2. We can always group similar character together with the above operation.

Example : ccbbcbc and we want to accumulate c’s.

at prefix len 4 reverse to get bbcccbc

at prefix len 5 reverse to get cccbbbc

at prefix len 6 reverse to get bbbcccc

This way any similar character can be grouped together.

3. We want to accumulate all the smallest to the end. Then we perform one final reverse.

Example: abaaca we accumulate all a’s to the end and then reverse it.

so it becomes cbaaaa and then we do one final reverse to get aaaabc.

If smallest is always accumulated to the end. It is guaranteed that we would get the lexicographically smallest string.

4. Note here that we can only group one character at a time. We cannot group two characters. Therefore we always consider the current smallest character scanned up till now for grouping since that would give us lexicographically smallest.

Example : dsdcacdfac. Here till 3rd index(1 indexed) ‘d’ is smallest. Therefore we group d’s up till this point and we get the string sddcacdfac. But after it we get c as the next smallest character so we start grouping ‘c’. Then at index 5 we hit a global minimum which is ‘a’ so only a’s can be grouped.

steps till index 3, group d’s to get : sddcacdfac

at index 5 we reverse to get : acddscdfac

at index 8 we reverse again to get : fdcsddcaac

finally at index 9 we reverse to get the smallest : aacddscdfc

Ideally we would like the c’s and d’s together also but since we can only group one at a time we prioritize the smallest to achieve the lexicographically smallest string.

Try to find the answer for example in given in point 1. You can verify your answer from the code below.